gpt4 book ai didi

c - C中的双向匿名管道

转载 作者:行者123 更新时间:2023-11-30 17:14:24 24 4
gpt4 key购买 nike

我已经用 Ubuntu 用 C 语言编写了这个(希望是正确的)匿名管道,但我无法双向连接。我怎样才能以最简单的方式解决这个问题,从 child 到 parent 以及从 parent 到 child ?

int main() {
int ret_val;
int pfd[2];
char buff[32];
char string1[]="String for pipe I/O";

ret_val = pipe(pfd);

if (fork() == 0) {
// child
close(pfd[0]); // close the read end
ret_val = write(pfd[1],string1,strlen(string1)); /*Write to pipe*/
if (ret_val != strlen(string1)) {
printf("Write did not return expected value\n");
exit(2); // Print error message and exit
}
}
else {
// parent
close(pfd[1]); /* close the write end of pipe */
ret_val = read(pfd[0],buff,strlen(string1)); /* Read from pipe */
if (ret_val != strlen(string1)) {
printf("Read did not return expected value\n");
exit(3); /* Print error message and exit */
}
printf("parent read %s from the child program\n",buff);

}
exit(0);
}

最佳答案

见下文,它只能以这种方式工作,因为管道是 4KB 缓冲并且字符串较小,否则可能会陷入死锁。

#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main() {
int ret_val;
int pfd[2];
int dfp[2];
char buff[32];
char string1[]="String for pipe I/O";
char string2[]="String 2 for pipe I/O";

ret_val = pipe(pfd), pipe(dfp);

pid_t pid = fork();
if (0 > pid) {
printf("Error forking\n");
exit(1);
}
if (pid == 0) {
// child
close(pfd[0]); // close the read end
close(dfp[1]); // close the write end
ret_val = write(pfd[1],string1,strlen(string1)); /*Write to pipe*/
if (ret_val != strlen(string1)) {
printf("Write did not return expected value\n");
exit(2); // Print error message and exit
}
ret_val = read(dfp[0],buff,strlen(string2)); /* Read from pipe */
if (ret_val != strlen(string2)) {
printf("Read did not return expected value\n");
exit(3); /* Print error message and exit */
}
printf("child read '%s' from the parent program\n",buff);
}
else {
// parent
close(pfd[1]); /* close the write end of pipe */
close(dfp[0]); /* close the read end */
ret_val = write(dfp[1],string2,strlen(string2)); /*Write to pipe*/
if (ret_val != strlen(string2)) {
printf("Write did not return expected value\n");
exit(2); // Print error message and exit
}
ret_val = read(pfd[0],buff,strlen(string1)); /* Read from pipe */
if (ret_val != strlen(string1)) {
printf("Read did not return expected value\n");
exit(3); /* Print error message and exit */
}
printf("parent read '%s' from the child program\n",buff);
wait(NULL);
}
exit(0);
}

关于c - C中的双向匿名管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30357911/

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