1

Hello guys so my code is supposed to create an unlimited amount of processes each running their own program and communicating threw pipes..

This is done in a recursive way so that the first parent creates a pipe then a child.. After this the child does the same creating a pipe2 and child2 etc....

Problem is that the parent process doesn't want to wait for all the children to be created and when I try to insert

waitpid(childpid, NULL, 0);

it kinda waits forever... So either I want the last child to send some kind of STOP WAIT signal or I would like another way to solve this problem!

Here is the code:

/* workForce.c
 * 
 * Program created by ----Secret-----
 * 
 * Input has to be the programs you wish the workForce to execute with following parameters seperated by '0's
 * 
 * example input:
 * printenv 0 grep L 0 sort
 * 
 * Will result in the command: printenv | grep L | sort | chosen PAGER
 * 
 * The program will pipe each unit of the workForce to the next unit untill it reaches the last unit where
 * it will printout the result to STDOUT.
 */
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define PIPE_READ_SIDE ( 0 )
#define PIPE_WRITE_SIDE ( 1 )

pid_t childpid; /* för child-processens PID vid fork() */

/*
 * The generateWorkforce method automaticly creates it's own workforce with one process per taskset
 * Each unit in the work force will execute the parameters provided
 * As long as it's not the end of the workforce the unit will pipe its output to the next unit
 */
void generateWorkforce(int taskpointer, int totaltasks, int taskset[], char* tasks[]){
/* Create pipe then fork */
int pipe_filedesc[ 2 ];
int return_value;
return_value = pipe( pipe_filedesc );
if( -1 == return_value ) {perror( "Cannot create pipe" ); exit( 1 );}

childpid = fork();

if( 0 == childpid )
{
    /* Redirecting STDIN to now read from pipe instead and removing the pipe */
    return_value = dup2( pipe_filedesc[ PIPE_READ_SIDE], STDIN_FILENO );
    if( -1 == return_value){perror( "Cannot dup" ); exit( 1 );}     
    return_value = close( pipe_filedesc[PIPE_READ_SIDE] );
    if( -1 == return_value ){perror( "Cannot close read end" ); exit( 1 );}
    return_value = close( pipe_filedesc[ PIPE_WRITE_SIDE ] );
    if( -1 == return_value ){perror( "Cannot close write end" ); exit( 1 );}

    if(taskpointer < totaltasks-1){
        generateWorkforce((taskpointer+taskset[taskpointer]), totaltasks, taskset, tasks);
    }
    else {
        kill(getppid, SIGINT);
        execlp(tasks[taskpointer], tasks[taskpointer], (char *) 0);

        /* exec only returns if an error occured */
        perror( "Cannot exec execute[pointer]" );
        exit( 1 );
    }
}
else
{
    if( -1 == childpid ){   perror( "Cannot fork()" );  exit( 1 );} 

    /* Redirecting STDOUT to write to pipe instead and thereafter removes the pipe */
    return_value = dup2( pipe_filedesc[ PIPE_WRITE_SIDE], STDOUT_FILENO );
    if( -1 == return_value){perror( "Cannot dup" ); exit( 1 );}
    return_value = close( pipe_filedesc[ PIPE_WRITE_SIDE ] );
    if( -1 == return_value ){perror( "Cannot close write end" ); exit( 1 );}
    return_value = close( pipe_filedesc[ PIPE_READ_SIDE ] );
    if( -1 == return_value ){perror( "Cannot close read end" ); exit( 1 );}

    waitpid(childpid, NULL, 0);

    /* Will define what task to execute and how many parameters it needs */
    if(taskset[taskpointer] > 1){
        char* execute[taskset[taskpointer]+1];
        int i;
        char* executeHead = tasks[taskpointer];
        execute[0] = tasks[taskpointer];
        for(i = 1;i<taskset[taskpointer];i++){
            execute[i] = tasks[taskpointer+i];
        }

        execute[taskset[taskpointer]] = (char *) 0;

        (void) execvp( executeHead, execute );
    }
    else{
        (void) execlp( tasks[taskpointer], tasks[taskpointer], (char *) 0 );
    }

    /* exec only returns if an error occured */
    perror( "Cannot exec tasks[taskpointer]" );
    exit( 1 );

}
}

int main( int argc, char * argv[] )
{
/* The following block will determine how many tasksets was in the input */
char * separator = "0";
int i;
int j;
int tasknr = 1;
for(i = 1, j = 1;i<(argc);i++)
{
    if(!(strcmp(argv[(i)], separator ))){
        j++;
    }
    else{
        tasknr++;
    }
}

char* execute[tasknr];
int taskset[j+1];

/* Will fill the taskset array and execute array */
if(getenv("PAGER")) execute[(tasknr-1)] = getenv("PAGER");
else execute[(tasknr-1)] = "less";
taskset[j] = 1;
taskset[0] = 0;
int k = 0;
for(i = 1, j = 0;i<(argc);i++)
{
    if(!(strcmp(argv[(i)], separator ))){
        j++;
        taskset[j] = 0;
    }
    else{
        execute[k] = argv[i];
        taskset[j]++;
        k++;
    }
}

generateWorkforce(0, tasknr, taskset, execute);

exit( 0 );
}

EDIT: the kill(getppid, SIGINT); was an attempt to stop the wait!

9
  • -1 != waitpid( pid, &status, WNOHANG ) <<< can you use that in the mainloop?
    – Jekyll
    Dec 1, 2013 at 13:58
  • Changed the waitpid I had for that, but it ended up being the same as not waiting at all. Dec 1, 2013 at 14:04
  • So the main(starter) process creates a child and the child creates another one - like a process list, correct? And you want the main proc to not wait at all, right?
    – Chris
    Dec 1, 2013 at 15:03
  • I want it to wait until the final child is done, but after that resume executing Dec 1, 2013 at 16:36
  • 1
    unrelated to the wait() issue: I find it much easier to understand if the processes are created in a loop e.g., see Connecting n commands with pipes in a shell?. And the code based on it: pipeline-three-processes.c
    – jfs
    Dec 2, 2013 at 9:26

1 Answer 1

2

As we said in the comments you need to use semaphores and implement synhcronisation between the two processes.
Semaphores can be counting but also binary. More about POSIX semaphores, here.

What you need to create is called a process chain, and can be easily made with a loop, as @J.F.Sebastian said.
You've asked to use POSIX semaphores, but be aware that POSIX IPC is not fully implemented in all systems, as SystemV is.

Some info:
When a process is forked, its memory is copied to the memory segment of the new process. If you want to use a semaphore with sem_init (unnamed semaphore) you will have to use shm_open, mmap and shmget to place the semaphore at a shared memory region so that the two processes can use it properly. You can (and should) read all about it here and here.

In order to simplify my solution, I've used a named semaphore, with sem_open. I create the semaphore firstly and initiallize it with value == 0 and then with a loop, all the needed processes are forked.

The main process, identified by its pid, is blocked with a sem_wait call. The last child now, notifies the main process with a sem_post call, that it has been created.

Here is the code that implements all these:

#include <stdio.h>
#include <semaphore.h>
#include <stdlib.h> 
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/file.h>
#include <errno.h>


#define PROCS_NO 3
#define chneg(r,s) { if (r < 0) {perror(s); exit(EXIT_FAILURE);}}


int main(void) 
{
    //check argument count
    //check input, for the sake of simplycity I'll use a #defined value
    pid_t childpid = 0;
    int i;
    sem_t* sem;
    pid_t mainproc = getpid();

    sem = sem_open("notify", O_CREAT | O_EXCL, 0644, 0); 
    /* name of semaphore is "notify", semaphore is reached using this name */
    chneg(sem_unlink("notify"), "sem_unlink");
    /* unlink prevents the semaphore existing forever */
    /* if a crash occurs during the execution         */

    for (i = 0; i < PROCS_NO; i++)
    {
        sleep(1);
        printf("\nAbout to create child %d\n", i);
        childpid = fork();
        if (childpid < 0) {
            perror("Fork error"); return -1;
        }
        if (childpid == 0) {
            //child process, continue the loop
        }
        else 
            break; //parent process, exit the loop
    }
    if (getpid() == mainproc) {
        //main process must wait for the last process to be created
        chneg(sem_wait(sem), "sem_wait");
        printf("\nMain Process: Just woke up\n");
        /* cleanup semaphores */
        chneg(sem_destroy (sem), "sem_destroy");
        exit (0);
    } 
    else {
        //child processes
        if (i == PROCS_NO -1 )
        {
            printf("\nLast child, going to sleep for 3\"\n");
            sleep(3);
            printf("\nJust woke up, waking up, main process as well\n");
            chneg(sem_post(sem), "sem_post");
            int semval;
            chneg(sem_getvalue(sem, &semval), "getvalue");
            printf("\nExiting with sem == %d\n", semval);
        }
        exit (0);
    }
}
2
  • Just a thought would something like this work the same: I create a flag (boolean=false) and do a while(boolean=false) loop and then in the last child I would set this boolean to true.. It's just a thought now I'll go looking in to semaphores thanks :) Dec 3, 2013 at 6:47
  • @David: What there would be in that loop? Watch out because processes don't share the same memory segment. Each process has one of its one. If you want the variable to change something at the loop of all processes, then you'd have to put this var at a shared memory segment. But don't do that, because you will then need a mutex semaphore as well, to protect race conditions upon reading and writing to the boolean variable. It's better to use semaphores. If there's anything else you need, do ask!:) Also,if this answer has helped you, you can accept my answer by clicking the "tick" icon,thank you!
    – Chris
    Dec 3, 2013 at 8:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.