'/bin/cat :Bad file descriptor
I am pretty new to the pipe(), fork() functions and /bin. I would like to pass a value through a pipe from my first child to my second child that I will later use to change the value. However, I thought that if I make line
and just line++
in the second child, it would be okay. However, line
would then become a shared value. So I used /bin/cat
to properly call out the stdout but I can't seem to get it to work.
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<string.h>
#include<sys/wait.h>
#include<stdio.h>
#include<unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#define READ_END 0
#define WRITE_END 1
int fd1[2];
char line[100];
int main()
{
int line = 1;
char *args[] = {"/bin/cat",NULL};
//child 1 process
if(fork() == 0)
{
close(fd1[READ_END]);
dup2(fd1[WRITE_END], WRITE_END);
printf("Num 1: %d\n", line);
close(fd1[WRITE_END]);
exit(0);
}
// child 2 process
if (fork() == 0)
{
close(fd1[WRITE_END]);
line++;
dup2(fd1[READ_END], READ_END);
printf("Num 2: %d\n", line);
close(fd1[READ_END]);
execv("/bin/cat",args);
exit(0);
}
else if(fork() != 0);
// Write input string and close writing end of first pipe.
close(fd1[READ_END]);
close(fd1[WRITE_END]);
exit(0);
return 0;
}
My output is:
Num 1: 1
Num 2: 2
/bin/cat: -: Bad file descriptor
/bin/cat: closing standard input: Bad file descriptor
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|