When Child process calls a function lost output
int handleCommand(char *command) {
pid_t pid;
pid = fork();
if (pid > 0) {
sleep(0.5);
} else if (pid == 0) {
execCommand(command);
//strcat(path[0], command);
//printf("%s", path[0]);
//execve(path[0], path, NULL);
//printf("\n");
} else {
printf("ERROR");
}
}
int execCommand(char *command) {
char* path[] = {"/bin/", NULL};
printf("in execCommand > %s", command );
strcat(path[0], command);
execve(path[0], path, NULL);
printf("\n");
}
at first as you can see i put the code dir开发者_Go百科ectly in the function where the fork takes place. This would display the output expected when executing the ls command for example. But when I moved this to a function i no longer see any output.
First note that the printf()
operations after the execve()
are never executed if the command is executed - execve()
only returns on error, never on success.
Next, unless you include a newline at the end of the output, the print won't be flushed to the terminal that is standard output (and there are circumstances, such as piping the standard output to another program, where even a newline is not necessarily sufficient to flush standard output). So, you should include a newline in the message, and still do fflush(stdout);
before the execve()
.
精彩评论