gpt4 book ai didi

创建新流程并期待输出

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

我正在编写一个程序,最终用于让一个子进程通过管道将随机生成的字符发送到另一个子进程以转换为大写值并输出,但在我到达那一步之前,我正在尝试创建子进程并做出一些预期的输出。我编写了以下应用程序:

#include <stdio.h> /* printf, stderr, fprintf */
#include <sys/types.h> /* pid_t */
#include <unistd.h> /* fork */
#include <stdlib.h> /* _exit */
#include <errno.h> /* errno */

int main()
{
pid_t writer;
pid_t reader;

writer = fork();
if (writer == -1)
{
fprintf(stderr, "can't fork, error %d\n", errno);
exit(1);
}

if (writer == 0)
{
printf("Writer process created.\n");
reader = fork();
if (reader == -1)
{
fprintf(stderr, "can't fork, error %d\n", errno);
exit(1);
}

if (reader == 0)
{
printf("Reader process created.\n");
kill(reader);
printf("Reader was successfully murdered.\n");
}
kill(writer);
}
wait();
printf("Writer killed.\n");
return 0;
}

理想情况下,我希望输出如下:

Writer process created.
Reader process created.
Reader was successfully murdered.
Writer killed.

但此时,它输出:

Writer process created.
Reader process created.
Reader was successfully murdered.
Writer killed.
Writer killed.
Writer killed.

就好像它正在经历父进程的整个代码迭代,以及从创建它们开始的两个子进程,这也让我相信它们没有在适当的时间被杀死我希望他们这样做。有人能指出我正确的方向吗?

最佳答案

这是您使用管道的完整工作示例(它们还同步进程,因此您不必终止它们)。请记住,读者进程正在阅读非常低效(一个字符 - 我将把它作为练习留给你 :))

#include <stdio.h> /* printf, stderr, fprintf */
#include <sys/types.h> /* pid_t */
#include <unistd.h> /* fork */
#include <stdlib.h> /* _exit */
#include <errno.h> /* errno */
#include <string.h> /* strlen */

int main()
{
pid_t writer;
pid_t reader;
char buf;
int pipefd[2] = {-1,-1};
const char* pcszTextToChild = "Text sent to child";

writer = fork();
if (writer == -1)
{
fprintf(stderr, "can't fork, error %d\n", errno);
exit(1);
}

if (writer == 0)
{/* writer process */
printf("Writer process created.\n");
if(pipe(pipefd) == -1)
{
perror("pipe");
exit(EXIT_FAILURE);
}
reader = fork();
if (reader == -1)
{
fprintf(stderr, "can't fork, error %d\n", errno);
exit(1);
}

if (reader == 0)
{/* reader process */
close(pipefd[1]); /* Close unused write end */
printf("Reader process created.\n\tReading: ");
fflush(stdout);
while (read(pipefd[0], &buf, 1) > 0)
write(STDOUT_FILENO, &buf, 1);
write(STDOUT_FILENO, "\n", 1);
close(pipefd[0]);
printf("Exiting reader process.\n");
exit(EXIT_SUCCESS);
}
else
{/* writer process */
close(pipefd[0]); /* Close unused read end */
write(pipefd[1], pcszTextToChild, strlen(pcszTextToChild));
close(pipefd[1]); /* Reader will see EOF */
wait(NULL); /* Wait for child */
printf("Exiting writer process.\n");
exit(EXIT_SUCCESS);
}
}
wait();
return 0;
}

结果:

Writer process created.
Reader process created.
Reading: Text sent to child
Exiting reader process.
Exiting writer process.

关于创建新流程并期待输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9593283/

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