logo
down
shadow

C, getting a parent and child process to work using signals


C, getting a parent and child process to work using signals

By : user2950954
Date : November 17 2020, 11:58 AM
I hope this helps you . I'm attempting to get my child process to generate a random number between 1 -9, then send it to my parent process for which it would display it to screen each time control + Z is pressed. I'm also using dup2() to change the stream from printf and scanf to the read and write ends of the pipe for each process. , The comment/code:
code :
//wait for control+C
if (signal(SIGINT, handleSignal) == SIG_ERR)
        if (secondSel == 1)
        {   
            pipe1 = pipe(fd);
        }   
        if (pipe1 < 0)
        {   
            printf("Error creating pipe 1 \n");
            exit(1);
        } 
        if (secondSel == 1)
        {   
            if (pipe(fd) < 0)
            {
                fprintf(stderr, "Error creating pipe 1\n");
                exit(1);
            }
        }
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

static void err_syserr(const char *fmt, ...);

int selection = 0;
int secondSel = 0;
int fd[2];
int pipe1 = 0;
pid_t fork1 = 0;

static void handleSignal(int sig)
{
    if (sig == SIGINT)
    {
        selection = 1;
        secondSel = 1;
    }
    if (sig == SIGTSTP)
    {
        selection = 1;
    }
}

int main(void)
{
    // wait for control+C
    if (signal(SIGINT, handleSignal) == SIG_ERR)
    {
        printf("Error catching signal C\n");
        exit(1);
    }
    //printf("Waiting for interrupt\n");
    //pause();

    while (1)
    {
        fprintf(stderr, "Looping: %d (%d)\n", (int)getpid(), selection);
        // wait till control c is pressed
        if (selection == 1)
        {
            signal(SIGINT, SIG_IGN);

            if (secondSel == 1)
            {
                pipe1 = pipe(fd);
                fprintf(stderr, "Created pipe: %d (%d, %d)\n", pipe1, fd[0], fd[1]);
            }
            if (pipe1 < 0)
            {
                printf("Error creating pipe 1\n");
                exit(1);
            }

            if (secondSel == 1)
            {
                fork1 = fork();
                fprintf(stderr, "Forked: %d (%d, %d)\n", fork1, (int)getpid(), (int)getppid());
            }

            if (fork1 < 0)
            {
                printf("Error with first fork.\n");
                exit(1);
            }
            else if (fork1 == 0) // first child process
            {
                signal(SIGTSTP, handleSignal);
                fprintf(stderr, "Pausing C: %d\n", (int)getpid());
                pause();
                fprintf(stderr, "Unpaused C: %d\n", (int)getpid());
                printf("a\n");
                if (close(fd[0]) != 0)
                    err_syserr("close(fd[0]=%d) failed", fd[0]);
                if (dup2(fd[1], 1) < 0)
                    err_syserr("dup2(fd[1]=%d, 1) failed", fd[1]);
                int randNum1 = rand() % 9 + 1;

                fprintf(stderr, "Print C: %d\n", randNum1);
                if (printf("%d\n", randNum1) < 2)
                {
                    fprintf(stderr, "Print C: failed\n");
                    clearerr(stdout);
                }
                fflush(stdout);
                if (close(fd[1]) != 0)
                    err_syserr("close(fd[1]=%d) failed", fd[1]);
            }
            else // parent
            {
                signal(SIGTSTP, handleSignal);
                fprintf(stderr, "Pausing P: %d\n", (int)getpid());
                pause();
                fprintf(stderr, "Unpaused P: %d\n", (int)getpid());
                printf("b\n");
                if (close(fd[1]) != 0)
                    err_syserr("close(fd[1]=%d) failed", fd[1]);
                if (dup2(fd[0], 0) < 0)
                    err_syserr("dup2(fd[0]=%d, 0) failed", fd[0]);
                int f = 99;
                if (scanf("%d", &f) != 1)
                {
                    fprintf(stderr, "Scanf P: failed\n");
                    clearerr(stdin);
                }
                printf("Parent: %d\n", f);
                if (close(fd[0]) < 0)
                    err_syserr("close(fd[0]=%d) failed", fd[0]);
            }
            secondSel = 0;
        }
    }
    return 0;
}

#include <errno.h>
#include <string.h>
#include <stdarg.h>

static void err_syserr(const char *fmt, ...)
{
    int errnum = errno;
    va_list args;
    if (fork1 != 0)     /* Parent waits 1/4 second */
        usleep(250000);
    fprintf(stderr, "%d: ", (int)getpid());
    va_start(args, fmt);
    vfprintf(stderr, fmt, args);
    va_end(args);
    if (errnum != 0)
        fprintf(stderr, ": %d %s", errnum, strerror(errnum));
    fputc('\n', stderr);
    exit(EXIT_FAILURE);
}
$ ./sigbug
Looping: 23528 (0)
Looping: 23528 (0)
…
…huge numbers of 'looping' messages omitted…
…
Looping: 23528 (0)
Looping: 23528 (0)
Looping: 23528 (0)
Looping: 23528 (0)
^CLooping: 23528 (0)
Looping: 23528 (0)
Looping: 23528 (0)
Looping: 23528 (0)
Created pipe: 0 (3, 4)
Forked: 23529 (23528, 45428)
Pausing P: 23528
Forked: 0 (23529, 23528)
Pausing C: 23529
^ZUnpaused C: 23529
Unpaused P: 23528
a
b
Print C: 5
Looping: 23529 (1)
Pausing C: 23529
Parent: 5
Looping: 23528 (1)
Pausing P: 23528
^ZUnpaused P: 23528
b
Unpaused C: 23529
23529: close(fd[0]=3) failed: 9 Bad file descriptor
23528: close(fd[1]=4) failed: 9 Bad file descriptor
$
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

static void handleSignal(int sig)
{
    return;
}

int main(void)
{
    int fd[2];
    int pipe1 = 0;
    pid_t fork1 = 0;

    if (signal(SIGINT, handleSignal) == SIG_ERR)
    {
        printf("Error catching signal C\n");
        exit(1);
    }

    printf("Waiting for interrupt\n");
    pause();
    signal(SIGINT, SIG_IGN);

    pipe1 = pipe(fd);
    if (pipe1 < 0)
    {
        fprintf(stderr, "Error creating pipe 1\n");
        exit(1);
    }
    fprintf(stderr, "Created pipe: %d (%d, %d)\n", pipe1, fd[0], fd[1]);

    fork1 = fork();
    if (fork1 < 0)
    {
        fprintf(stderr, "Error with fork.\n");
        exit(1);
    }

    fprintf(stderr, "Forked: %d (%d, %d)\n", fork1, (int)getpid(), (int)getppid());
    signal(SIGTSTP, handleSignal);

    if (fork1 == 0)
    {
        dup2(fd[1], 1);
        close(fd[0]);
        close(fd[1]);
        while (1)
        {
            fprintf(stderr, "Pausing C: %d\n", (int)getpid());
            pause();
            fprintf(stderr, "Unpaused C: %d\n", (int)getpid());
            int randNum1 = rand() % 9 + 1;
            fprintf(stderr, "Print C: %d\n", randNum1);
            if (printf("%d\n", randNum1) < 2)
            {
                fprintf(stderr, "Print C: failed\n");
                clearerr(stdout);
            }
            fflush(stdout);
        }
    }
    else
    {
        dup2(fd[0], 0);
        close(fd[0]);
        close(fd[1]);
        while (1)
        {
            fprintf(stderr, "Pausing P: %d\n", (int)getpid());
            pause();
            fprintf(stderr, "Unpaused P: %d\n", (int)getpid());
            int f = 99;
            if (scanf("%d", &f) != 1)
            {
                fprintf(stderr, "Scanf P: failed\n");
                clearerr(stdin);
            }
            else
                printf("Parent: %d\n", f);
        }
    }

    return 0;
}
$  ./sigbug-jl1
Waiting for interrupt
^CCreated pipe: 0 (3, 4)
Forked: 23554 (23553, 45428)
Pausing P: 23553
Forked: 0 (23554, 23553)
Pausing C: 23554
^ZUnpaused C: 23554
Print C: 5
Unpaused P: 23553
Pausing C: 23554
Parent: 5
Pausing P: 23553
^ZUnpaused C: 23554
Print C: 8
Unpaused P: 23553
Pausing C: 23554
Parent: 8
Pausing P: 23553
^ZUnpaused P: 23553
Unpaused C: 23554
Print C: 6
Pausing C: 23554
Parent: 6
Pausing P: 23553
^\Quit: 3
$


Share : facebook icon twitter icon
How can I send messages (or signals) from a parent process to a child process and viceversa in Perl?

How can I send messages (or signals) from a parent process to a child process and viceversa in Perl?


By : Hubert Austin
Date : March 29 2020, 07:55 AM
will help you Use kill. If you set a variable in the parent before your fork, you don't need any external options.
code :
my $parent_pid = $$; # Keep a reference to the parent

my $pid = fork();
if ($pid) {
    print "Im going to wait (Im the parent); 
    my child is: $pid. The part Im going to use is: $partId \n";
    push(@childs, $pid);
} 
elsif ($pid == 0) {
   my $slp = 5 * $_;
   print "$_ : Im going to execute my code (Im a child) and Im going to wait like $slp seconds. The part Im going to use is: $partId\n";
   sleep $slp;
   print "$_ : I finished my sleep\n";

   kill 20, $parent_pid # Send a signal to the parent, 20 is SIGCHLD

   exit($slp);
} 
Sending signals between parent and child process

Sending signals between parent and child process


By : Imran Sobir
Date : March 29 2020, 07:55 AM
around this issue You are committing many signal no-nos in your program. The most insidious problem that I see is one of racing. There is a window of opportunity between the time you fork and the time you register a signal handler for the child during which a SIGUSR1 can be sent and lost.
Looking at your specific code, imagine a situation where you fork, the parent gets the first chance to run, sends SIGUSR1 to the child before the child ever established a handler and this signal is lost forever. The simplest way to solve this problem is to establish the SIGUSR1 signal handler before forking.
Passing signals between parent and child process in C

Passing signals between parent and child process in C


By : Can Sayan
Date : March 29 2020, 07:55 AM
this one helps. I'm just referring to the documentation for these functions—I have no experience using them.
It appears what sigfillset() is going to do is load the process signal mask into your sigset_t. This means that your sigset_t is going to contain the set of signals that are currently blocked by your process. I assume the default is nothing is blocked, so the set would be empty.
nodejs send signals to child process does not work

nodejs send signals to child process does not work


By : Dharmesh D. Dave
Date : March 29 2020, 07:55 AM
Hope that helps The first problem is that you spawn a child process and then immediately send it SIGINT. Since the child process (probably) hasn't run at all yet, it hasn't registered for that signal and thus is killed by it. The easiest way to get this working is to just put it in a setTimeout:
code :
setTimeout(function() {
  child.kill('SIGINT');
}, 100);
data from child: child calling
setInterval(function() {
  console.log('hey!');
}, 1000);
fork and signal: how to send signals from parent process to specific child process

fork and signal: how to send signals from parent process to specific child process


By : Robert de Almeida Bo
Date : March 29 2020, 07:55 AM
it should still fix some issue you could use the popen() function to open a process by forking and opening a pipe to that process (instead of using fork() directly)
The parent knows the PID of each process so can then easily pass the pid of the second child to the first child.
Related Posts Related Posts :
  • How to transmit data from an interrupt handler to an user application?
  • Why do I get the error "bash: ./a.out: Permission denied" when I execute a C program in Linux mint 15
  • syntax of sigchld and its declaration
  • error using g_idle_add() in C++, same thing works in C
  • why if else or nested if else are called single statement in C
  • How do I interpret this printf in C
  • load the functions of a shell script without executing it
  • Is FilterSendNetBufferLists handler a must for an NDIS filter to use NdisFSendNetBufferLists?
  • How to write to flash memory using inline assembly?
  • More Return Statements vs. More Indentation
  • How to show an image on a PictureBox from resource?
  • Having malloced some memory,I could't calculator the proper size of the memories I malloced.I don't know why
  • What is the main difference between integer pointer and character pointer?
  • Why are some functions declared extern and header file not included in source in Git source code?
  • what is the use of fflush(stdin) in c programming
  • Is it safe to return file File descriptor locally allocated from another function In C
  • Changing undefined values of an array
  • What does an empty parameter list mean?
  • using strtol on a string literal causing segmentation fault
  • Same structure objects memory overlap?
  • C-Linux-Any way to pass command "history" to Linux shell?
  • Using #define in defining string size C
  • How to use thread pool and message queues in Multithreaded Matrix Multiplication?
  • Can't find how to select path to run a C program
  • Automatic variable in C not initialized but given fixed value within loop
  • main() function defined without return type gives warning
  • Output of following code with integer, float, char variable
  • why buffer memory allocation error in opencl
  • Why am I getting this error during run-time?
  • Strange behaviour of the pow function
  • task in increment , decrement , printf() , why these are evaluated in this manner in C
  • 28 extra bytes in bss
  • Waiting for multiple events without polling
  • Why are my variables reporting as "undeclared identifier" when compiling?
  • Correct AddNode function but somehing happens when I printf
  • When I traverse in the splay tree, then now which one is root?
  • Data type conversion in Postfix evaluation
  • No output in terminal (Head First C)
  • Data writes over after realloc
  • function: findnextchar() doesn't work
  • Getting file-size property from Nautilus
  • Forward declare entities in C standard library?
  • Static array in C
  • Function signature indicates return type void*, but returns pointer of a different type
  • How do I measure time per thread in C?
  • Online judgeProblem (Wrong Answer)
  • Use function pointer initialized in other source file
  • last line of file is duplicated using fscanf
  • How to print files with same month of modification using directory in c?
  • ADT Circular Queue enqueue and dequeue
  • What events can cause ferror to return non-zero?
  • Accessing dynamically allocated structure received through socket
  • Vim with C Conditional Parsing
  • C can pointers be aligned with any other data type?
  • sdcc inline asm() not working
  • I/O - Manipulation of C Strings
  • sscanf 1 byte hex data without overflow
  • Avoid division by zero in C when taking log with respect to a random number
  • C - memory corruption with threads
  • Why does my program sometimes returns 0xc0000005 and sometimes runs well?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org