I have these two files and i call exec.c from main.c using exec(). As far as I understand exec.c should inherit the pipe but it says there is no link pipe in exec.c. What is the problem here?
main.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define die(e) \
do \
{ \
fprintf(stderr, "%s\n", e); \
exit(EXIT_FAILURE); \
} while (0);
int main(int argc, char *argv[])
{
int link[2];
pid_t pid;
char foo[4096];
if (pipe(link) == -1)
die("pipe");
if ((pid = fork()) == -1)
die("fork");
if (pid == 0)
{
dup2(link[1], STDOUT_FILENO);
close(link[0]);
close(link[1]);
execvp("./exec", argv);
die("execl");
}
else
{
close(link[1]);
int nbytes = read(link[0], foo, sizeof(foo));
printf("Output: (%.*s)\n", nbytes, foo);
wait(NULL);
}
return 0;
}
exec.c
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/shm.h>
int main(int argc, char *argv[])
{
char a;
a='A';
write(link[1],&a,sizeof(a));
return 0;
}
I am just practicing and want to output the data that is save from pipe()
What I am doing wrong, can you help me to debug? TIA!
CodePudding user response:
In the main.c
program you connect the pipe through standard output of the child process.
That means the child process passes information to the parent process through its normal standard output.
From this follows that the exec.c
program could be as simple as this:
#include <stdio.h>
int main(void)
{
printf("A");
}
More specifically, your exec.c
Source file doesn't have any idea of the pipe, and definitely not about the variable link
, and will simply fail to build.