gpt4 book ai didi

c - Linux:使用管道在进程之间发送信息

转载 作者:太空宇宙 更新时间:2023-11-04 13:03:23 24 4
gpt4 key购买 nike

管道是用 fd[] 和 fd1[] 创建的。我正在用管道写作。当我引用 STDIN_FILENO 时,拿两个管道给了我错误,所以我删除了它。我只是用管道读写。现在它仍然没有从管道中读取。带有文件描述符 fd[] 的管道有效。但 fd1[] 没有。

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

int main(int argc, char *argv)
{

int fd[2];
pid_t childpid;
pipe(fd);
int fd2[2];
pipe(fd2);
int array[5] = {1,2,3,4,5};
int array2[5] = {11,12,13,14,15};
//fprintf(stderr,"size%ld",sizeof(int));

//char buffer[111];
int *subarr1;

int buffer_num;
int status;

if ((childpid = fork()) == 0) {
fprintf(stderr,"\nProcess:%d Parent:%d",getpid(),getppid());

//dup2(fd[1], STDOUT_FILENO);
close(fd[0]); //read end
write(fd[1],array,100);
close(fd[1]);
//execl("/bin/ls", "ls", "-l", NULL);
perror("The exec of ls failed\n");

if ((childpid = fork()) == 0)
{
fprintf(stderr,"\nProcess:%d Parent:%d",getpid(),getppid());

//dup2(fd2[1], STDOUT_FILENO);
close(fd2[0]); //read end
write(fd2[1],array2,sizeof(array2));
close(fd2[1]);
//execl("/bin/ls", "ls", "-l", NULL);
perror("The exec of ls failed\n");
}
else
{// parent
wait(NULL);
}
}
else {
wait(&status);
fprintf(stderr,"\nTHis is parent");
subarr1 = (int*)malloc(sizeof(int)*(5));
fprintf(stderr,"\nProcess:%d Parent:%d",getpid(),getppid());

//dup2(fd[0], STDIN_FILENO);
close(fd[1]);

int j;
for(j=0;j<5;j++)
{
read(fd[0],&buffer_num,sizeof(int));
subarr1[j] = buffer_num;
//printf("%s",buffer);

}

for(j=0;j<5;j++)
{
fprintf(stderr,"\n%d\n",subarr1[j]);
}

close(fd[0]);//read end


//dup2(fd2[0], STDIN_FILENO);
buffer_num = 0;

close(fd2[1]);
//read(fd2[0],&buffer_num,100);

for(j=0;j<5;j++)
{
read(fd2[0],&buffer_num,sizeof(int));
subarr1[j] = buffer_num;
//printf("%s",buffer);

}

for(j=0;j<5;j++)
{
fprintf(stderr,"\n%d\n",subarr1[j]);
}
//fprintf(stderr, "\nThis is second pipe%s", buffer);
close(fd2[0]);


/*//printf("\nAAAAAAAA%s\n",buffer);
dup2(fd2[0], STDIN_FILENO);
close(fd2[1]);
printf("\nAAAAAAAA%s\n",buffer);

read(fd2[0],buffer,100);
printf("%s",buffer);
close(fd2[0]);//read end
printf("\nAAAAAAAA%s\n",buffer);

*/
//execl("/usr/bin/sort", "sort", "-n", NULL);
perror("The exec of sort failed\n");
}

return 0;

}

最佳答案

这个调用:

read(fd2[0],&buffer_num,100);

尝试从本地 (int) 变量 buffer 开始将 100 个字节读入内存,因此覆盖它之后堆栈上的任何其他内容,粉碎堆栈并导致未定义的行为(可能在某些时候崩溃点)。

您的 write 调用也有类似的问题,从更小的对象写入 100 个字节,但那些可能只写入您随后忽略的垃圾,而不是导致崩溃(尽管这同样是未定义的行为)。

关于c - Linux:使用管道在进程之间发送信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33323693/

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