我写了下面的代码:
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include <sys/types.h>
#include <sys/wait.h>
#define BUFF 200
int main(int argc, char *argv[]) {
char write_buffer[BUFF];
char read_buffer[BUFF];
strcpy(write_buffer, "This string supposed to be sent from parent to child");
int fds[2];
pid_t pid;
if ((pid=fork())==-1) {
perror("fork error");
}
if (pipe(fds)==-1) {
perror("pipe error");
}
else if (pid==0) { // child
int bytes;
if ((bytes=read(fds[0], read_buffer, BUFF))==-1) {
perror("read error");
}
else {
printf("read %d bytes from pipe\n", bytes);
}
}
else { // parent
if (write(fds[1], write_buffer, strlen(write_buffer))==-1) {
perror("write error");
}
printf("FLAG to check if write() went through\n"); // this will print!
wait(NULL);
}
}
上面的简单代码是尝试通过管道从父进程向子进程发送数据。
问题是,由于某种原因,执行被暂停了……
子进程在 read() 系统调用处被阻塞(或者至少看起来是这样),而父进程只是坐在那里,等待它完成,但这种情况从未发生过。
这里有什么问题?显然,父进程有足够的时间将 write_buffer
写入管道,因此子进程不会在空管道上调用 read()。
最佳答案
您fork
然后创建管道,这样每个进程都将转到自己的一组管道,这些管道不会相互通信。
只需切换代码并在 fork
之前调用 pipe
就可以了。
此外,尽管在这里可能无关紧要,但请养成循环读写的习惯。 read
和 write
不能保证在一次调用中获取或放入您请求的所有数据。同样,完成后关闭管道。关闭管道的写入端将向读取器发出信号,表明已到达文件末尾。
while (read(fds[0], read_buffer, sizeof(read_buffer)) > 0)
{
//process bytes read
}
关于c - 从管道读取时进程暂停 - linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23429449/