C pointer principle (88)-LINUX applications (1)

Source: Internet
Author: User

1. on the linux platform, each thread can have dedicated data:

# Include

# Include
Struct mydata {
Int x;
Char c [4];
};
Pthread_t pthreada, pthreadb;
Pthread_key_t datakey; // each process is created once. Different threads and keys with the same name point to different places.


Void * cleanup_mydata (void * dataptr) {//
Free (struct mydata *) dataptr );
}
Void anum1 (){
Int rc;
Struct mydata * mdata = (struct mydata *) malloc (sizeof (struct mydata ));
Mdata-> x = 1;
Mdata-> c [0] = 'a ';
Mdata-> c [1] = '\ 0 ';
Rc = pthread_setspecific (datakey, (void *) mdata); // you can specify the value to which the key points. Note that the mdata value is the memory and must be directed to the memory by pointer.
Sleep (1 );
Struct mydata * mmdata = (struct mydata *) pthread_getspecific (datakey); // retrieves the value pointed to by the key. Note that this mdata is the memory value and must be directed to the memory by pointer.
Printf ("-% d-% s \ n", mmdata-> x, mmdata-> c );
Fflush (stdout );
}
Void bnum2 (){
Int rc;
Struct mydata * mdata = (struct mydata *) malloc (sizeof (struct mydata ));
Mdata-> x = 2;
Mdata-> c [0] = 'B ';
Mdata-> c [1] = '\ 0 ';
Rc = pthread_setspecific (datakey, (void *) mdata); // you can specify the value to which the key points. Note that the mdata value is the memory and must be directed to the memory by pointer.
Sleep (1 );
Struct mydata * mmdata = (struct mydata *) pthread_getspecific (datakey); // retrieves the value pointed to by the key. Note that this mdata is the memory value and must be directed to the memory by pointer.
Printf ("-% d-% s \ n", mmdata-> x, mmdata-> c );
Fflush (stdout );
}


Int main (void ){


Int rc;


Rc = pthread_key_create (& datakey, cleanup_mydata); // indicates the cleanup function when the key is deleted.
Pthread_create (& pthreada, NULL, anum1, NULL );
Pthread_create (& pthreadb, NULL, bnum2, NULL );
Sleep (3 );
Pthread_join (pthreada, NULL );
Pthread_join (pthreadb, NULL );
Rc = pthread_key_delete (datakey); // only deletes the key, but does not delete the memory pointed to by the value. The thread stops calling the User-Defined delete function. In this example, cleanup_mydata is used.

}

2. Touch shell

All content of this blog is original, if reproduced please indicate the source http://blog.csdn.net/myhaspl/

Implemented through the execlp function. The execlp function is used to execute files.

Its Parameters and descriptions are as follows:

#include 
  
   int execlp( const char * file,             const char * arg0,             const char * arg1,            …             const char * argn,             NULL );
  
Arguments:
File
Used to construct a pathname that identifies the new process image file. if the fileargument contains a slash character, the file argument is used as the pathname for the file. otherwise, the path prefix for this file is obtained by a search of the directories passed as the environment variable PATH.
Arg0 ,..., Argn
Pointers to NULL-terminated character strings. these strings constitute the argument list available to the new process image. terminate the list terminated with a NULL pointer. the arg0 argument must point to a filename that's associated with the process.

Waitpid ()

Wait for process termination

Function
SYNOPSIS DESCRIPTION PARAMETERS RETURN VALUES CONFORMANCE MULTITHREAD SAFETY LEVEL PORTING ISSUES AVAILABILITY SEE ALSO
SYNOPSIS

# Include

# Include

Pid_t waitpid (pid_t pid, int * stat_loc, int options );

DESCRIPTION

TheWaitpid ()Function lets the calling process obtain status information about one of its child processes. if status information is available for two or more child processes, the order in which their status is reported is unspecified. if more than one thread is suincluded inWaitpid ()Awaiting termination of the same process, exactly one thread returns the process status at the time of the target child process termination. The other threads return-1,ErrnoSetECHILD.

If the calling process setsSIGCHLDToSIG_IGN, And the process has no unwaited for children that were transformed into zombie processes, the calling thread blocks until all of the children of the process terminate, at which timeWaitpid ()Returns-1ErrnoSetECHILD.

If the parent process terminates without waiting for all of its child processes to terminate, the remaining child processes are assigned a new parent process ID corresponding to a system-level process.

PARAMETERS

Pid

Specifies a set of child processes for which the status is requested:

  • If pid is equal to-1, status is requested for any child process. In this respect,Waitpid ()Is equivalentWait ().
  • If pid is greater than 0, it specifies the process ID of a single child process for which status is requested.
  • If pid is 0, status is requested for any child process whose process group ID is equal to that of the calling process. This setting is not currently supported.
  • If pid is less than-1, status is requested for any child process whose process group ID is equal to the absolute value of pid. This setting is not currently supported.
    Stat_loc

    Specifies the location to which the child process 'exit status is stored. IfNULLIs passed, no exit status is returned. Otherwise, the following macros defined in Can be used to evaluate the returned status:

    WIFEXITED (s)

    Evaluates to a non-zero value if status was returned for a child process that exited normally.

    WEXITSTATUS (s)

    If the valueWIFEXITED (s)Is non-zero, this macro evaluates to the low-order 8 bits of the status argument that the child process passedExit ()Or_ Exit (), Or to the value that the child process returned fromMain ().

    WIFSIGNALED (s)

    Evaluates to a non-zero value if status was returned for a child process that terminated due to receept of a signal that was not caught.

    WTERMSIG (s)

    If the valueWIFSIGNALED (s)Is non-zero, this macro evaluates to the number of the signal that caused the termination of the child process.

    WIFCORED (s)

    Evaluates to a non-zero value if status was returned for a child process that terminated due to receept of a signal that was not caught, and whose default action is to dump core.

    WCOREDUMP (s)

    Evaluates to a non-zero value if status was returned for a child process that terminated due to receept of a signal that was not caught, and whose default action is to dump core.

    WCORESIG (s)

    If the valueWIFCORED (s)Is non-zero, this macro evaluates to the number of the signal that caused the termination of the child process.

    WIFSTOPPED (s)

    Evaluates to a non-zero value if status was returned for a child process that is currently stopped.

    WSTOPSIG (s)

    If the valueWIFSTOPPED (s)Is non-zero, this macro evaluates to the number of the signal that caused the child process to stop.

    Options

    Is the bitwise random sive-OR of zero or more of the following flags, defined in :

    WNOHANG

    TheWaitpid ()Function does not suspend execution of the calling thread if status is not immediately available for one of the child processes specified by pid.

    WUNTRACED

    The status of any child processes specified by pid that are stopped, and whose status has not yet been reported since they stopped, is also reported to the requesting thread. this value is currently not supported, and is ignored.

    RETURN VALUES

    IfWaitpid ()Was invokedWNOHANGSet in options, and there are children specified by pid for which status is not available,Waitpid ()Returns 0. IfWNOHANGWas not set,Waitpid ()Returns the process ID of a child when the status of that child is available. Otherwise, it returns-1 and setsErrnoTo one of the following values:

    ECHILD

    The process or process group specified by pid does not exist or is not a child of the calling process.

    EFAULT

    Stat_loc is not a writable address.

    EINTR

    The function was interrupted by a signal. The value of the location pointed to by stat_loc is undefined.

    EINVAL

    The options argument is not valid.

    ENOSYS

    Pid specifies a process group (0 or less than-1), which is not currently supported.



    The procedure is as follows:
    # Include
    # Include




    # Define MAXLINE 100
    // Execlp simulated SHELL




    Int main (void ){
    Int pid;
    Int jg, status, len;
    Char buf [MAXLINE];




    Printf ("\ n # myhaspl ~~ "); // Custom shell prompt
    While (fgets (buf, MAXLINE, stdin )! = NULL) {// read a row
    Len = strlen (buf)-1;
    If (buf [len] = '\ n') {// removes line breaks. execlp only accepts the end of NULL.
    Buf [len] = 0;
    }
    Pid = fork ();
    If (pid <0 ){
    Printf ("fork error! \ N ");
    }
    Else if (pid = 0) {// sub-process
    Printf ("\ n ");
    If (buf [0] = 'q' & strlen (buf) = 1) {// type Q to exit shell
    Exit (200 );
    }
    Jg = execlp (buf, buf, (char *) 0 );
    If (jg =-1) {// Error
    Printf ("cannot be executed: % s \ n", buf );
    Exit (127 );
    }
    Exit (0 );
    }
    If (jg = waitpid (pid, & status, 0) <0) {// parent process
    Printf ("waitpid error \ n ");
    }
    If (WEXITSTATUS (status) = 200) {// calculate the return value of WEXITSTATUS
    Printf ("exit... \ n ");
    Break;
    }
    Printf ("\ n # myhaspl ~~ "); // Custom shell prompt
    }
    Exit (0 );
    }
    Run:
    Deepfuture @ deepfuture-laptop :~ /Private/mytest $ gcc-o test21 test21.c
    Test21.c: In function 'main ':
    Test21.c: 15: warning: incompatible implicit declaration of built-in function 'strlen'
    Test21.c: 26: warning: incompatible implicit declaration of built-in function 'eg'
    Test21.c: 28: warning: incompatible implicit declaration of built-in function 'execlp'
    Test21.c: 31: warning: incompatible implicit declaration of built-in function 'eg'
    Test21.c: 33: warning: incompatible implicit declaration of built-in function 'eg'
    Test21.c: 44: warning: incompatible implicit declaration of built-in function 'eg'
    Deepfuture @ deepfuture-laptop :~ /Private/mytest $./test21


    # Myhaspl ~~ Ls


    1 pvmtest test20 testbswap testmul. s x
    Ex.txt test test20.c testbswap. s testmutex x. c
    Gmon. out test12.s test21 test. c testmutex. c xx
    Hello test13 test21.c test. c ~ Testpopen xx. c
    Hello. c test13.c test2.c testmes testpopen. c xx.txt
    Hello. o test15 test6 testmes. c testpvm1.c xxx.txt
    Hello. s test15.c test66 testmesrecv testpvm2.c xxxx.txt
    Main test19 test66.s testmesrecv. c testpx xy
    Main. c test19.c test6.c testmessnd testpx1
    Main. c ~ Test1.c testasmc testmessnd. c testpx1.s
    Myhello.txt test2 testasmc. c testmul testpx. s


    # Myhaspl ~~ Xx


    Cannot Execute: xx


    # Myhaspl ~~ Q


    Exit ....
    All content of this blog is original, if reproduced please indicate the source http://blog.csdn.net/myhaspl/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.