gpt4 book ai didi

c - fork() 和 system() 调用无法正常工作

转载 作者:太空宇宙 更新时间:2023-11-04 01:05:45 25 4
gpt4 key购买 nike

我正在玩 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 缓冲了您的消息,并且没有立即将其输出到标准输出。在这种情况下,当您的子进程随后被终止时,您对 printf 的调用将完全不会被注意到。

尝试在消息末尾添加 \n 以强制 printf 刷新其内部缓冲区:

printf("Song complete...\n");

关于c - fork() 和 system() 调用无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23587529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com