Why the printf function doesn't work?

Hi everyone,I write an application myself, but I find that the printf function doesn'st work
does anyone know why?

int main(int argc, char *argv[])
{
	int c;
        printf("main ......\n");   // cannot display
	while((c = getopt(argc, argv, "sv:")) != -1) {
		switch (c) {
		case 's':
			print_to_syslog = 0;
			break;
		case 'v': {
			char *end;
			long l;
			l = strtoul(optarg, &end, 0);
			if(*optarg == 0 || *end != 0 || l > LOG_LEVEL_MAX) {
				ERROR("Invalid loglevel %s", optarg);
				exit(1);
			}
			log_level = l;
			break;
		}
		default:
			return -1;
		}
	}
       ....

Aren't you missing <stdio.h>?

Yes, I didn't include the stdio.h header file, but why does it can compile without errors?
I will try again.

I included the stdio.h in another header file, so it can compile without errors.

On what platform are you doing this, Linux, macOS, Windows?
And how do you compile it, using plain gcc main.c or something else (cmake, autoconf)?

It really should work if you start the resulting executable from a shell, well always does for me at least.

Linux environment、CMake tool and procd

cmake_minimum_required(VERSION 3.12)

PROJECT(uswitch C)

set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads)

ADD_DEFINITIONS(-Os -Wall -Werror --std=gnu99 -g3 -Wmissing-declarations -Wno-error=missing-declarations -I${CMAKE_SOURCE_DIR})

ADD_EXECUTABLE(uswitchd packet.c worker.c ubus.c ht.c learn.c main.c)
TARGET_LINK_LIBRARIES(uswitchd ubox ubus Threads::Threads)

SET(CMAKE_INSTALL_PREFIX /)

INSTALL(TARGETS uswitchd
	RUNTIME DESTINATION sbin
)
INSTALL(FILES scripts/mac-address-table
	DESTINATION sbin
)
#!/bin/sh /etc/rc.common
# Copyright (c) 2021 OpenWrt.org

START=50

USE_PROCD=1
PROG=/sbin/uswitchd

start_service() {
        procd_open_instance
        procd_set_param command "$PROG"
        procd_set_param respawn
        procd_close_instance
}

I see, I'm not really familiar with procd, Sorry. But since procd is launching you app stdout is maybe not going to the terminal.

Others will for sure be able to help you more. And a search in the forum about procd and stdout may help.

Turn on redirection to logd.

         procd_set_param stdout 1 # forward stdout of the command to logd
         procd_set_param stderr 1 # same for stderr
5 Likes

Thank you very much, this guide helped me a lot.

1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.