.8 Process (01)

来源:互联网 发布:购物返利源码 编辑:程序博客网 时间:2024/06/03 16:58

process control provided by the UNIX System


1.PID

pid:0 ---> scheduler process          (system kerenel proc)

pid:1 ---> init process            (normal user proc)  /etc/rc* , /etc/inittab ,  /etc/init.d/  


E.g:

int main(int argc, char *argv[]){        pid_t t1,t2;        uid_t t3,t4;        gid_t t5,t6;        t1=getpid();        t2=getppid();        t3=getuid();        t4=geteuid();        t5=getgid();        t6=getegid();        printf("--------------- test pid --------------------\n");        printf("pid: %d\n",t1);        printf("ppid: %d\n",t2);        printf("uid: %d\n",t3);        printf("euid: %d\n",t4);        printf("gid: %d\n",t5);        printf("egid: %d\n",t6);        return 0;}


Find the user's uid gid and other uid member

E.g:

int main(int argc, char *argv[]){        char    _name[256];        struct group    *pGr=NULL;        int     _count=0;        char    *_mem = NULL;        printf("******* Just Only Finding *******\n");        printf("input the name you want to search:");        scanf("%s",_name);        // -------------- find from input Name -------------        struct passwd   *ptr=NULL;        setpwent();        while( (ptr = getpwent())!=NULL)        {                if(strcmp(_name,ptr->pw_name)==0)                        break;        }        endpwent();        // -------------- output pw_xxx Uid Info ------------        if(ptr)        {                printf("uid=%d\n",ptr->pw_uid);                printf("gid=%d\n",ptr->pw_gid);                printf("dir=%s\n",ptr->pw_dir);                printf("pwd=%s\n",ptr->pw_passwd);                printf("cmd=%s\n",ptr->pw_shell);        }        else        {                printf("there's no ID called %s\n",_name);                exit(0);        }        // -------------- group check -----------------------        printf("-------------- GID: %d ------------\n",ptr->pw_gid);        setgrent();        while( (pGr = getgrent())!=NULL)        {                if(pGr->gr_gid==ptr->pw_gid)                        break;        }        endgrent();        if(pGr)        {                for(_count=0; _count < 1000; _count++)                {                        if(pGr->gr_mem[_count]!=NULL)                        {                                _mem = pGr->gr_mem[_count];                                printf("%04d [%s]: %s \n",_count,pGr->gr_name,_mem);                        }                        else                        {                                break;                        }                }        }        exit(0);}



2. Fork()  called once but returns twice


The reason the child's process ID is returned to the parent is that a process can have more than one child, and there is no function that allows a process to obtain the process IDs of its children.

we never know whether the child starts executing before the parent or vice versa.

int     glob = 6;       /* external variable in initialized data */char    buf[] = "a write to stdout\n";intmain(void){    int       var;      /* automatic variable on the stack */    pid_t     pid;    var = 88;    if (write(STDOUT_FILENO, buf, sizeof(buf)-1) != sizeof(buf)-1)        err_sys("write error");    printf("before fork\n");    /* we don't flush stdout */    if ((pid = fork()) < 0) {        err_sys("fork error");    } else if (pid == 0) {      /* child */        glob++;                 /* modify variables */        var++;    } else {        sleep(2);               /* parent */    }    printf("pid = %d, glob = %d, var = %d\n", getpid(), glob, var);    exit(0);}


* race conditions

synchronize a parent and a child : 

we simply have the parent put itself to sleep for 2 seconds, to let the child execute


* strlen() PK sizeof()  aboutstring

strlen() ---> in execute tiem  function call

sizeof() --->value in compile time operator

                    (above case: the buffer is initialized with a known string, and its size is fixed)


* stand output buffer

$ ./a.outa write to stdoutbefore forkpid = 430, glob = 7, var = 89      child's variables were changedpid = 429, glob = 6, var = 88      parent's copy was not changed$ ./a.out > temp.out$ cat temp.outa write to stdoutbefore forkpid = 432, glob = 7, var = 89before forkpid = 431, glob = 6, var = 88
Indeed, one characteristic offork is that all file descriptors that are open in the parent are duplicated in the child.

* why the fork() fail --- two reasons:

 (a) if too many processes are already in the system, which usually means that something else is wrong

 (b) if the total number of processes for this real user ID exceeds the system's limit. 

       that CHILD_MAX specifies the maximum number of simultaneous processes per real user ID.



3. File sharing in Parent & Child by Fork()

It is important that the parent and the child share the same file offset.

fork() --------- exec()    

two separate functions in UNIX

separating the two allows the child to change the per-process attributes between the fork and the exec


vfork()

1) provides an efficiency gain on some paged virtual-memory implementations of the UNIX System.

2) guarantees that the child runs first, until the child callsexec orexit

    When the child calls either of these functions, the parent resumes.


4. Eixt  functions()

    1)  eixt() --- ISO  C    -------------- a)  calling the  atexit();   b) close all the std IO streams     std library call

    2)  _Exit() --- ISO  C  -------------- without singal() ,without atexit() 

    3)  _exit() --- POSIX.1  --------------- kernel system call 

    4)  returnfrom the start routine of the last thread in the process.   --->  process exit code = 0 

    5)  Calling thepthread_exit function from the last thread in the process.  --->  process exit code = 0

     | 

1~3 )  ---------> parsing the exit status code to Parent Process.

4~5 )  ---------> kernel generates a status code for abnormal reason 

     |

Parent process :  either thewaitor thewaitpidfunction  -----------------   return code ; 


* If parent process dead before the child ,  Init process  as  parent .



5. wait & waitPid 

#include <sys/wait.h>pid_t wait(int *statloc);pid_t waitpid(pid_t pid, int *statloc, int options);

Process terminate ----------> SIGCHLD signal ----------->  Parent Process : 


a) ignore this signal 

b) signal handler ( ) 


Return :

  • Block, if all of its children are still running

  • Return immediately with the termination status of a child, if a child has terminated and is waiting for its termination status to be fetched

  • Return immediately with an error, if it doesn't have any child processes


More than one children proc Case:

wait()  --- >  returns on termination of any of the children

waitpid() --- >  

The interpretation of the pid argument for waitpid depends on its value:pid == 1 Waits for any child process. In this respect, waitpid is equivalent to wait. pid > 0 Waits for the child whose process ID equals pid. pid == 0 Waits for any child whose process group ID equals that of the calling process. (We discuss process groups in Section 9.4.) pid < 1 Waits for any child whose process group ID equals the absolute value of pid. 


Error :

wait() ---> has no children | interrupted by a signal 

waitpid() ---> not exist or is not a child of the calling process