PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 22, 2022

[FIXED] How to communicate from children process(exec) with parent through pipe()?

 July 22, 2022     c, exec, fork, linux, process     No comments   

Issue

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!


Solution

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.



Answered By - Some programmer dude
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing