我需要在 C 中创建无名管道而不使用 fork();
我有带 fork 的代码,但我找不到任何有关不带 fork 的无名管道的信息。我读到这是一个旧的解决方案,但它只是需要它。谁能帮我吗?
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define KOM "Message to parent\n"
int main()
{
int potok_fd[2], count, status;
char bufor[BUFSIZ];
pipe(potok_fd);
if (fork() == 0) {
write(potok_fd[1], KOM, strlen(KOM));
exit(0);
}
close(potok_fd[1]);
while ((count = read(potok_fd[0], bufor, BUFSIZ)) > 0)
write(1, bufor, count);
wait(&status);
return (status);
}
最佳答案
你应该更精确一点,你需要它做什么?仅在同一进程中向自己发送消息没有多大意义。
无论如何,您实际上可以不 fork 并在一个进程内完成所有操作,这并不是真正有用。
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#define KOM "Message to parent\n"
int main()
{
int potok_fd[2], count;
char bufor[BUFSIZ];
pipe(potok_fd);
write(potok_fd[1], KOM, strlen(KOM));
fcntl(potok_fd[0], F_SETFL, O_NONBLOCK);
while ((count = read(potok_fd[0], bufor, BUFSIZ)) > 0)
write(1, bufor, count);
return 0;
}
关于c - C 中没有 fork 的无名管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53033210/