gpt4 book ai didi

c - 子进程和父进程之间的 pipe()

转载 作者:太空狗 更新时间:2023-10-29 15:28:33 26 4
gpt4 key购买 nike

我为子进程和父进程之间的 pipe() 编写了这段代码。我需要确保这是否是正确的代码。顺便说一句,它给出了应该看到的答案!

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



int main(int argc, char *argv[]){
pid_t pid;
int fd[2];
char buf[20];

pipe(fd);


switch(pid = fork()){

case -1:
perror("pipe");
exit(1);

case 0:
/*child process*/
close(fd[1]);
read(fd[0], buf, 20);
printf("Child read message from parent: %s\n", buf);
exit(1);
break;

default:
/*parent process*/
close(fd[0]);
write(fd[1], "Hello from parent\n", 17);
break;
}
return 0;

}

最佳答案

switch 语句基本上没问题,尽管您不需要 pid 变量,因为您没有对它做任何事情。

父代码也大部分没问题,但字符串实际上是 18 个字节,没有 NUL 终止符,19 个字节有 NUL 终止符。处理子项中的换行符和 NUL 终止符是一种很好的做法,因此我会坚持使用 17 并从字符串中删除换行符。

子代码错误。您需要一个变量来存储 read 的返回值。您需要检查返回值以确保 read 成功。并且您需要在字符串中添加一个 NUL 终止符。在 C 编程语言中,“字符串” 是以零字节结尾的字符数组(称为 NUL 终止符,写为 '\0')。您的工作是确保您使用的缓冲区始终足够大以容纳 NUL 终止符,并且每个字符串都有一个 NUL 终止符。

所以固定的代码是这样的:

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

int main( void )
{
int fd[2];
char buffer[20];

if ( pipe(fd) < 0 ) {
perror( "pipe" );
exit( 1 );
}

switch( fork() ) {
case -1:
perror( "fork" );
exit( 1 );

case 0:
/*child process*/
close(fd[1]);
ssize_t count = read( fd[0], buffer, sizeof(buffer)-1 );
if ( count <= 0 ) {
perror( "read" );
exit( 1 );
}
buffer[count] = '\0';
printf( "Child read message from parent: %s\n", buffer );
exit(1);

default:
/*parent process*/
close(fd[0]);
char *message = "Hello from parent";
size_t length = strlen( message );
write( fd[1], message, length );
break;
}

return 0;
}

关于c - 子进程和父进程之间的 pipe(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40268454/

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