NEXT UP previous
Next: My Home Page

Answers

  1. Your solution will use getpid() and getpgrp() to get the process ID and process group ID. If these are the same then the process is a process group leader, and not otherwise.

  2. Your solution will use getuid() and geteuid() to get the process real user ID and effective user ID. If these are not the same then the process is running set UID, and not otherwise.

  3. The code for this question is very straightforward, as follows:
    	main()
    	{
    		if (fork())
    			printf("parent PID = %d\n", getpid()); 
    		else
    			printf("child PID = ·/.d\n", getpid());
    	}
    
    In general, some flavors of UNIX will run the parent process first, others will run the child first, and yet others have no fixed order. In Linux, the current source code for fork() shows that the parent process should always run first, and your experiments should bear this out.

  4. The whole idea behind adding exit() and wait() to a program is to force the parent to wait for execution of the child to terminate before it proceeds. The new code appears as:
    	#include <sys/wait.h>
    
    	main()
    	{
    		int status;
    
    		if (fork())
    		{
    
    			wait (&status);
    			printf("parent PID = %d, child ", getpid()); 
    			printf("exit status = %d\n", WEXITSTATUS(statval));
    		}
    		else
    		{
    			printf("child PID = %d\n", getpid(); 
    			exit (55);
    		}
    	}
    
    When this is run, the use of exit() and wait ensure that the child message will always be displayed first, and this applies not only to Linux, but to any version of UNIX as well.

  5. The best way to guarantee a particular order of execution for the three commands is to fork() child processes to execute each of the commands in turn making the parent wait() for the termination of one child process before executing the next:
    	main()
    	{
    		if (!fork())
    		{
    			execlp("cp", "cp"  "/etc/fstab", ".", 0); 
    			printf("error executing cp\n"); 
    			exit(1);
    		}
    		wait (0);
    
    		if (!fork())
    		{
    			execlp("sort", "sort", "fstab", "-o", "myfstab", 0); 
    			printf("error executing sort\n");
    			exit(1);
    		}
    		wait (0);
    		execlp("cat", "cat", "myfstab", 0); 
    		printf("error executing cat\n"); 
    		exit(1)
    	}
    
    In order to simplify the code slightly the return value from fork() is not checked here for an error value. It would also be a good idea to check the exit status returned to wait() for and error value and deal with it appropriately. I leave these things for you to do...

NEXT UP previous
Next: My Home Page