Interview Question


Country: United States




Comment hidden because of low score. Click to expand.
1
of 1 vote

when a process calls fork to create a child, fork returns the pid of child
it does not change the pid of the process
getpid will still show it's original pid

if a process called fork 100 times, each time fork will return a different pid (of the children) but getpid in the parent process is always the same

- bigphatkdawg September 19, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Try this out:

pid_t pid;
for(i=0; i<20; i++) {
	if( ( pid_t = fork()) !=0 )  { //staying in parent space

		printf("Fork num. %d returned value: %ld\n", (long)pid);
		printf("After above fork, parent pid %ld\n, (long)getpid());
	}
	
}

- bigphatkdawg September 19, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

And fix the small bugs there :P

- bigphatkdawg September 19, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

bigphatkdawg, understood thanks for the explanation

- Ravi September 20, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Parent process PID will always remain same irrespective of number of forks. Adding some working code for benefit of all.

#include<stdio.h>
#include<unistd.h>

main() 
{
    pid_t parent = getpid();
    int i;

    for (i = 1; i <= 5; i++)
    {
        pid_t forkpid;
        pid_t curprocess = getpid();

        if (curprocess == parent)  // Make sure we don't get into infinite loop
        {
            forkpid = fork();
            curprocess = getpid(); // override value for child
        }

        if (parent == curprocess)
            printf("Fork number: %d, parent process id %ld\n", i, (long)curprocess);
        else
            printf("Iteration number: %d, child process id %ld\n", i, (long)curprocess);
    }
}

- Lucky October 03, 2014 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More