【发布时间】:2014-05-10 23:51:54
【问题描述】:
我正在使用 fork() 和 system() 命令,当我运行此示例代码时,我发现子进程在系统调用完成后没有打印“Song complete...”行。 这是正常的还是我错过了什么?
我认为 system() 会完成它的工作,然后返回子进程并继续愉快地退出或执行其他任务。此代码示例不会发生这种情况。
#include <sys/types.h> /* pid_t */
#include <sys/wait.h> /* waitpid */
#include <stdio.h> /* printf, perror */
#include <stdlib.h> /* exit */
#include <unistd.h> /* _exit, fork */
int main(void)
{
pid_t pid;
int i;
pid = fork();
if (pid == -1) {
/*
* When fork() returns -1, an error happened.
*/
perror("fork failed");
exit(EXIT_FAILURE);
}
else if (pid == 0) {
/*
* When fork() returns 0, we are in the child process.
*/
printf("Hello from the child process!\n");
system("aplay ./SOS_sample.wav");
printf("Song complete...");
_exit(EXIT_SUCCESS); /* exit() is unreliable here, so _exit must be used */
}
else {
/*
* When fork() returns a positive number, we are in the parent process
* and the return value is the PID of the newly created child process.
*/
int status;
printf("Waiting on the song to end...\n");
for (i = 0;i<10;i++){
printf("%d\n",i);
}
(void)waitpid(pid, &status, 0);
for (i=0;i<10;i++){
printf("%d\n",i);
}
}
return EXIT_SUCCESS;
}
【问题讨论】:
-
难道不是因为
printf正在缓冲您的消息而不是立即输出吗?尝试在消息末尾添加\n以刷新其缓冲区。 -
@HalimQarroum 完全正确。打印到
stderr或在printf之后致电fflush(stdout),您应该会看到您的期望。我相信换行符"\n"是否会导致刷新取决于系统。