gpt4 book ai didi

在父进程和子进程之间创建管道

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

我正在尝试在父进程和子进程之间创建一个管道。在这个管道中,子进程将写入数据,而父进程将读取并打印数据。我不知道为什么,但如果我输入一个大字符串,数据就会出错,对于包含 +- 7 个单词的字符串,它仍然可以正常工作。我猜这与缓冲区的大小有关,但无法修复它。

#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

/* in this code i will make a child process with fork command
then i will create pipe using pipe commands.
i will transfer data from the child process to the father process
omriziner code
*/

void main(int argc,char *argv[])
{
if(argc < 2){
printf("prototype error \n<Enter any data you wana write> \n");
return;
}

int fd[2]; // creating array with 2 places for 2 fd'stdio
// fd[0] is set to read file in the pipe
//fd[1] is set to write file in the pipe
int piperes;
pid_t childpid;
char buff[5];
char * data = "learning to the exam";
printf("father pid %d:\n",getpid());
printf ("size of data is %d \n",(int)sizeof(argv[1]));
printf ("size of buff is %d \n",(int)sizeof(buff));
piperes = pipe(fd);
if(piperes < 0){
perror("PIPE ERR");
exit(1);
}
printf("Pipe succeed \n");
if((childpid = fork()) == -1){ // fork will create a child process
perror("FORK ERR");
exit(1);
}
// when fork suceed - the pid of the child will return in the parent and 0 will return in the child
// when fork fail - the pid will be -1

printf("Fork succeed, fork return is %d and process pid is %d :\n",childpid,getpid());

if(childpid == 0){ // if pid zero , wer in the child prcs
close(fd[0]);
write(fd[1],argv[1],sizeof(argv[1])); // send data to the write fd of the pipe
printf("data was written to fd[1] by pid : %d \n",getpid());
exit(0);
}
else{ // in this case, we're in the father process
close(fd[1]);
read(fd[0],buff,sizeof(argv[1])+1);
printf("Recived data is ''%s''", buff);
printf("By pid : %d \n",getpid());
exit(1);
}
}

最佳答案

sizeof(argv[1])

这并不像你想象的那样。

sizeof 在编译时计算1,在本例中将返回 8(假设您使用的是 64 位计算机),因为 argv[1] 是一个指针。

因为您想要字符串的长度(只能在运行时知道),所以您应该使用:

strlen(argv[1])
<小时/>

1 - 在某些情况下,sizeof 在运行时进行评估。这不是其中之一。

关于在父进程和子进程之间创建管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38058319/

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