Hy to all! I have a problem, i try to write c program, where parent create two process. And first child write in console (printf()) "one" and the second one print "two". Both of them must print (printf()) their word 5 times. I don't know why don't work..
An example of print:
one
two
one
two
one
two
one
two
one
two

my code so far:

int main(int argc, char* argv[])
{
    int semid1;struct sembuf s;
    semid1 = semget(304, 2, IPC_EXCL | IPC_CREAT | 0600);
    semctl(semid1, 0, SETVAL,0);
    semctl(semid1, 1, SETVAL,1);

    int c; int t;
    int x=10;
    int id = getpid();
    pid_t tabPID[2];
    if(id==getpid())
    {
        int id2=getpid();
        while(x>0){
            for(c=0;c<2;c++)
            {
                if(id2==getpid()){
                    tabPID[c]=fork();
                    if(tabPID[c]==0 && id2==getppid()){

                        s.sem_num = 0;
                        s.sem_op = 1;
                        s.sem_flg = 0;
                        semop(semid1, &s, 0);

                        printf ("One\n");

                        s.sem_num = 0;
                        s.sem_op = -1;
                        s.sem_flg = 0;
                        semop(semid1, &s, 0);

                        s.sem_num = 1;
                        s.sem_op = -1;
                        s.sem_flg = 0;
                        semop(semid1, &s, 1);

                        printf ("Two\n");

                        s.sem_num = 1;
                        s.sem_op = 1;
                        s.sem_flg = 0;
                        semop(semid1, &s, 1);
                    }
                }
            }
            x-=1;
        }
        int co = 0;
        while(co<2)
        {
            wait(&tabPID[co]);
            co++;
        }
    }

    semctl(semid1, 0, IPC_RMID);
    semctl(semid1, 1, IPC_RMID);
    return 0;
}

Recommended Answers

All 3 Replies

I don't see any fork() calls in your code, which is how you would create multiple subserviant processes (parent create two processes). Those are not threads, but seperate processes that are created by the root process.

I have fork() call in line 19, tabPID[c]=fork();

When you say it doesn't work, could you be more presise? Is there no output, incorrect output, a crash?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.