I have the following code of a simple program which in it a father process sends a msg to child process with pipe
#include <unistd.h>
#include <stdio.h>
int main(){
int file_des[2];
pipe(file_des);
int ret = fork ;
if (ret == -1)
printf("error");
else if (ret > 0 ){ //father
close(file_des[0]);
printf("im the father sending msg :) \n");
write(file_des[1],"nadav",6*sizeof(char));
waitpid(ret);
}
else{ // son
char buffer[256];
close(file_des[1]);
printf("im the son reading dads msg :) \n");
read(file_des[0],buffer,6*sizeof(char));
printf("dads msg is %s\n",buffer);
}
}
but I get the following error (running with gdb) :
Program received signal SIGPIPE, Broken pipe.
0x00007ffff7b00870 in __write_nocancel () at ../sysdeps/unix/syscall-template.S:81
81 ../sysdeps/unix/syscall-template.S: No such file or directory.
where is the problem here ? what am I doing wrong ?
I guess the problem is here
int ret = fork ;
Instead of a function call like int ret = fork();
you assign a function pointer to the ret
variable, which casts implicitly to int
. Now your program acts like a parent process, but it didn't spawn any child actually. You close the read end of the pipe and ta da -- you write to the pipe with no readers.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.