Newbie
Newbie

Reputation: 1927

Execl and printing of child PID

I am trying to get the PID of the child process. But when I run execl, it prints out the PID of 0 and sometimes negative numbers instead of the real PID. However, if I remove the execl line, it works fine. Anyone knows why?

if (pid==0)
            { 
                    arrayPID[i] = getpid();
                 execl("/bin/ls","/bin/ls",NULL); 
            }

             printf ("Child PID is %i\n",arrayPID[i]);

Note that I know that the 2nd parameter of execl should be just "ls" but it seems to be working and I need it to be that way. Is it because of this?

I have also tried this but still give zero or negative values for PID.

if (pid==0)
            { 
                    arrayPID[i] = getpid(); 
            }
if (pid==0)
            { 
                 execl("/bin/ls","/bin/ls",NULL); 
            }

Do assume my other code is correct.

Thanks

Upvotes: 0

Views: 1676

Answers (2)

Dennis Meng
Dennis Meng

Reputation: 5187

I have a sneaking suspicion as to what might be happening. This extends Carl's answer some.

Assuming your code does something like this...(I can't be 100% sure without more details)

int pid = fork();
if (pid == 0) {
    arrayPID[i] = getpid();
    execl("/bin/ls","/bin/ls",NULL);
}
printf ("Child PID is %i\n",arrayPID[i]);

The issue is that you only enter that if statement in the child process, but not the parent process. The child process will call execl and unless something goes wrong, never reach the printf (though even if it does, it will print what you want).

Hence, in the parent process, if you did not initialize arrayPID[i] before this section of code, it'll still be uninitialized when it reaches the printf, and thus basically print out garbage (though I suppose 0 being most common isn't unusual).

Upvotes: 2

Carl Norum
Carl Norum

Reputation: 224944

fork() returns the PID of the child process to the parent process. Calling getpid in the child doesn't do anything.

What I guess you're looking for is:

pid_t pid = fork();
if (pid == 0)
{
    // child
    execl("/bin/ls", "ls", NULL);
}
else if (pid > 0)
{
    // parent
    printf("Child PID is %d\n", (int)pid);
}
else
{
    // error
    perror("fork failed");
}

Upvotes: 2

Related Questions