I have problem with process in c code with argv parameters

49 views Asked by At

Gcc compiler messages:

passing argument 1 of ‘srand’ makes integer from pointer without a cast [-Wint-conversion]

too many arguments for format [-Wformat-extra-args]

My code:

#include<stdlib.h>
#include<unistd.h>
#include<stdio.h>
#include<sys/wait.h>
void main(int argc,int* argv[])
{
    srand(argv[1]);
    srand(argv[2]);
    printf("I am orginal MY PID %d and MY PPID %d \n",getpid(),getppid());
    int pid,x,s,x1;
    pid=fork();
    if (pid!=0)//parent 
    {
        printf("I am parnet and My PID %d and My PPID %d /n",getpid(),getppid());
        for(int i=0 ;i<3;i++){
            s=rand();
            x=s%5;
            sleep(x);
            printf("parent sleep\n",x);
        }
        printf("the parent terminated with PID %d and PPID %d \n",getpid(),getppid());
    }
    else{//child
        printf("i'm a child with PID %d and PPID %d \n" ,getpid(),getppid());
      
        for(int i=0 ; i<3;i++){
            sleep(x1);
            s=rand();
            x1=s%5;
            }
            printf("child sleep \n",x1);
            printf("the child terminated with PID %d and PPID %d \n",getpid(),getppid());

    }
    

}

1

There are 1 answers

0
Vlad from Moscow On

For starters the function main shall be declared like

int main(int argc, char * argv[])

instead of

void main(int argc,int* argv[])

In any case the expressions argv[1] and argv[2] have a pointer type. So these calls of the function srand

srand(argv[1]);
srand(argv[2]);

are invalid. The function is declared like

void srand(unsigned int seed);

That is it expects an integer instead of a pointer.

And in any case before using argv[1] and argv[2] you need to check the value of argc.

And calling the function twice sequentially does not make sense.

In these calls of printf

printf("parent sleep\n",x);
//...
printf("child sleep \n",x1);

you specified the redundant arguments x and x1 that do not have corresponding conversion specifiers in the format string.

Also you are using uninitialized variables as for example

sleep(x1);

The variable x1 was not initialized.