exec function family, daemon, thread synchronization and mutex

Source: Internet
Author: User
Tags strcmp

2015.3.2

There are three different processes and procedures:
1, there are different locations, programs: Hard disk, disk. Process: Memory
2. The program is static and the process is dynamic

Execute the./a.out-->bash->bash Program Call Fork ()--and the child process will store the parameters after the./a.out to argv[]. Then call exec to process these parameters, and the last child process exits with the cursor flashing

Process into the Stop state: 1, debugging, 2, the foreground into the background to run

Threads: Each program is loaded into memory and can be created in one or more sequential streams (enabling the process to do more than once at the same time, each of which handles its own separate tasks)

callback function

Synchronization and Mutex

The basic usage reference for the EXEC function family:

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

void Printusage (const char *argv0)
{
fprintf (stderr,
"Usage:%s <exec type>\n"
"Exec type:execl\n"
"Execlp,\n"
"Execv,\n"
"Execvp\n",
ARGV0);
}

int main (int argc, char *argv[])
{
Char *vector[] = {"PS", "-F", NULL};

if (argc! = 2)
{
Printusage (Argv[0]);
return 1;
}

if (0 = = strcmp (argv[1], "execl"))
{
if (Execl ("/bin/ps", "PS", "-F", NULL) < 0)
{
Perror ("Execl error!");
}
}

else if (0 = = strcmp (argv[1], "EXECLP"))
{
if (EXECLP ("PS", "PS", "-F", NULL) < 0)
{
Perror ("EXECLP error!");
}
}

else if (0 = = strcmp (argv[1], "EXECV"))
{
if (Execv ("/bin/ps", vector) < 0)
{
Perror ("Execv error!");
}
}

else if (0 = = strcmp (argv[1], "EXECVP"))
{
if (EXECVP ("PS", vector) < 0)
{
Perror ("EXECVP error!");
}
}

Perror ("Note the program would not step the exec () function met some errors");

return 0;
}


Daemon creation and error handling: (daemon error, output error message to file, call log function Implementation)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcnl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main ()
{
pid_t PID, sid;
int i,fd;
Char *buf = "This is a daemon\n";

PID = fork ();

if (PID < 0)
{
printf ("Error fork\n");
Exit (1);
}

else if (PID > 0)
{
Exit (0);
}
Openlog ("Daemon_syslog", Log_pid,lod_daemon);

if (SID = Setsid ()) < 0)
{
Syslog (Log_err, "%s\n", "Setsid")
Exit (1);
}

if (SID = ChDir ("/")) < 0)
{
Syslog (Log_err, "%s\n", "Setsid");
Exit (1);
}

for (i = 0; i < getdtablesize (); i++)
{
Close (i);
}

while (1)
{
if (FD = open ("/tmp/daemon.log", o_creat| owronly| o_append.0600)) <0)
{
Syslog (Log_err, "open");
Exit (1);
}

Write (Fd,buf, strlen (BUF) + 1);
Close (FD);
Sleep (10);
}

Closelog ();
Exit (0);
}


Thread creation, end and recycle!

The related functions are as follows:

int Pthread_create (pthread_t *thread, pthread_attr_t *attr, void * (start_continue) (void *), void *arg);
void Pthread_exit (void *retval);
int Pthread_join (pthread_t thread, void **thread_result);
int pthread_cancle (pthread_t thread);

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

Char message[32] = "Hello World";
void *thread_function (void *arg);

int main (int argc, char *argv[])
{
pthread_t A_thread;
void *thread_result;

if (Pthread_create (&a_thread, NULL, thread_function, (void *) message) < 0)
{
Perror ("fail to Pthread_create");
Exit (-1);
}

printf ("Waiting for Thread to finish\n");

if (Pthread_join (A_thread, &thread_result) < 0)
{
Perror ("fail to Prhread_join");
Exit (-1);
}

printf ("Message is now%s\n", message);

return 0;
}

void *thread_function (void *arg)
{
printf ("Thread_function is Runing,argument is%s\n", (char *) arg);
strcpy (Message, "marked by thread");
Pthread_exit ("Thank you for the CPU time");
}


The above program compiles with this statement: GCC xxxx.c-lpthread-d _reentrant
-lpthread//Link Pthread Library
-D _reentrant//Generate re-entry code

Program Run Result:
[Email protected]:/mnt/hgfs/source test/file io$ gcc test13.c-lpthread-d_reentrant
[Email Protected]:/mnt/hgfs/source test/file io$./a.out
Waiting for thread to finish
Thread_function is runing,argument are Hello World
Message is now marked by thread


Create two threads, execute separate programs, and finally exit and recycle by the main program.

#include <string.h>
#include <pthread.h>

Char message1[] = "AAAAAAAAAA";
Char message2[] = "BBBBBBBBBB";
void *thread_function1 (void *arg1);
void *thread_function2 (void *arg2);


int main (int argc, char *argv[])
{
pthread_t a_thread1,a_thread2;
void *thread_result;

if (Pthread_create (&a_thread1, NULL, Thread_function1, (void *) Message1) < 0)
{
Perror ("fail to pthread_create 1");
Exit (-1);
}

if (Pthread_create (&a_thread2, NULL, Thread_function2, (void *) Message2) < 0)
{
Perror ("Fail to pthread_create 2");
Exit (-1);
}

printf ("Waiting for Thread to finish\n");

if (Pthread_join (A_thread1, NULL) < 0)
{
Perror ("fail to Prhread_join");
Exit (-1);
}

if (Pthread_join (A_thread2,null) < 0)
{
Perror ("fail to Prhread_join");
Exit (-1);
}

return 0;
}

void *thread_function1 (void *arg1)
{
int i;
for (i = 0; i < 3; i++)
{
printf ("string is%s \ n", (void *) arg1);
Sleep (1);
}

Pthread_exit ("Thread 1 is exit");
}


void *thread_function2 (void *arg2)
{
int i;
Sleep (10);
for (i = 0; i < 3; i++)
{
printf ("string is%s \ n", (void *) arg2);
Sleep (1);
}

Pthread_exit ("Thread 2 is exit");
}

The operation result of the above program:
[Email Protected]:/mnt/hgfs/source test/file io$./a.out
Waiting for thread to finish
String is BBBBBBBBBB
String is AAAAAAAAAA
String is BBBBBBBBBB
String is AAAAAAAAAA
String is BBBBBBBBBB
String is AAAAAAAAAA
[Email Protected]:/mnt/hgfs/source test/file io$


Synchronization between Threads:
The semaphore is a protected amount and can only be accessed through three operations:
1. Initialization
2.P Operations (Request resources)
3.V operations (freeing resources)

The value of the semaphore is a non-negative integer

The P operation contains the following:

if (signal volume > 0)
{
The task of requesting resources continues to run;
The value of the semaphore-1;
}
Else
{
The task of requesting resources is blocked;
}

The V operation contains the following content:

If (no task is waiting for resources)
{
The value of the semaphore + 1;
}
Else
{
Wake up the first waiting task to keep it running;
}

The usual semaphore manipulation functions involved in synchronization are as follows:

int Sem_init (sem_t *sem, int pshared, unsigned int value);
int sem_wait (sem_t *sem);
int Sem_post (sem_t *sem);
int sem_trywait (sem_t *sem);
int Sem_getvalue (sem_t *sem, int svalue);

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>

Char buf[60];
sem_t sem;
void *function (void * arg);

int main (int argc,char **argv)
{
pthread_t A_thread;
void *thread_result;
if (Sem_init (&sem,0,0) < 0)
{
Perror ("fail to Sem_init");
Exit (-1);
}

if (Pthread_create (&a_thread,null,function,null) < 0)
{
Perror ("fail to Pthread_create");
Exit (-1);
}

printf ("Input ' quit ' to exit\n");

Do
{
Fgets (buf, stdin);
Sem_post (&sem);
}while (strncmp (buf, "Quit", 4)! = 0);

return 0;
}

void *function (void * arg)
{
while (1)
{
Sem_wait (&sem);
printf ("You enter%d characters\n", strlen (BUF)-1);
}
}


Inter-process mutex: plus mutex lock

Some common functions involved in mutexes are as follows:

int Pthread_mutex_init (pthread_mutex_t *mutex, pthread_mutexattr_t *attr);
int Pthread_mutex_lock (pthread_mutex_t *mutex);
int Pthread_mutex_unlock (pthread_mutex_t *mutex);

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

#define _lock_

unsigned int value1, value2,count;
pthread_mutex_t Mutex;
void *function (void *arg);

int main (int argc,char * * argv)
{
pthread_t A_thread;

if (Pthread_mutex_init (&mutex,null) < 0)
{
Perror ("fail to Mutex_init");
Exit (-1);
}

if (Pthread_create (&a_thread, NULL, Function,null) < 0)
{
Perror ("fail to Pthread_create");
Exit (-1);
}

while (1)
{
count++;
#ifdef _lock_

Pthread_mutex_lock (&mutex);

#endif

value1 = count;
value2 = count;

#ifdef _lock_

Pthread_mutex_unlock (&mutex);

#endif
}

return 0;
}

void *function (void *arg)
{
while (1)
{

#ifdef _lock_

Pthread_mutex_lock (&mutex);

#endif

if (value1! = value2)
{
printf ("Count =%d, value1 =%d, value2 =%d\n", Count, Value1, value2);
Usleep (100000);
}

#ifdef _lock_

Pthread_mutex_unlock (&mutex);

#endif
}

return NULL;
}

Define _LOCK_ after shielding operation Result: (unshielded program no output, value1 and value2 equal)
[Email protected]:/mnt/hgfs/source test/file io$ gcc lock14.c-lpthread-d_reentrant
[Email Protected]:/mnt/hgfs/source test/file io$./a.out
Count = 3338702, value1 = 3338702, value2 = 3338701
Count = 53692966, value1 = 53692966, value2 = 53692965
Count = 89910265, value1 = 89910265, value2 = 89910264
Count = 125008213, value1 = 125008213, value2 = 125008212
Count = 149351134, value1 = 149351134, value2 = 149351133
Count = 171729575, value1 = 171729575, value2 = 171729574
Count = 228510044, value1 = 228510044, value2 = 228510043
Count = 256495259, value1 = 256495259, value2 = 256495258
Count = 287733530, value1 = 287733530, value2 = 287733529
Count = 324321776, value1 = 324321776, value2 = 324321775
Count = 365523395, value1 = 365523395, value2 = 365523394
Count = 420680808, value1 = 420680808, value2 = 420680807
Count = 448359597, value1 = 448359597, value2 = 448359596
Count = 494800004, value1 = 494800004, value2 = 494800003
Count = 528839826, value1 = 528839826, value2 = 528839825
^c
[Email protected]:/mnt/hgfs/source test/file io$ ^c
[Email Protected]:/mnt/hgfs/source test/file io$

Another reference program for mutual exclusion locks;

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define THREAD_NUM 3
#define REPEAT_NUM 3
#define DELAY_TIME_LEVELS 3.0

pthread_mutex_t Mutex;

void *thrd_func (void *arg)
{
int thrd_num = (int) arg;
int delay_time = 0;
int count = 0;
int res;

res = Pthread_mutex_lock (&mutex);

if (res)
{

printf ("Thread%d lock failed\n", thrd_num);
Pthread_exit (NULL);
}

printf ("Thread%d is starting\n", thrd_num);
for (count = 0; count < Repeat_num; count++)
{
Delay_time = (int) (rand () * delay_time_levels/(Rand_max)) + 1;

Sleep (Delay_time);
printf ("\tthread%d:job%d delay =%d\n",
Thrd_num,count, Delay_time);
}

printf ("Thread%d finished\n", thrd_num);
Pthread_mutex_unlock (&mutex);

Pthread_exit (NULL);
}

int main (void)
{
pthread_t Thread[thread_num];
int no = 0, tpid;
void *thrd_ret;

Srand (Time (NULL));

Pthread_mutex_init (&mutex,null);

for (no = 0; no < thread_num; no++)
{
Tpid = Pthread_create (&thread[no],null,thrd_func, (void *) NO);
if (tpid! = 0)
{
printf ("Create thread%d failed\n", no);
Exit (-1);
}
}

printf ("Create treates success\nwaiting for threads to finish...\n");

for (no = 0; no < thread_num; no++)
{
Tpid = Pthread_join (Thread[no],&thrd_ret);
if (Tpid = = 0)
{
printf ("Thread%d joined\n", no);
}
Else
{
printf ("Thread%d join failed\n", no);
}


}
Pthread_mutex_destroy (&mutex);

return 0;
}

The results of the above program run: (The results are different from the book, the analysis is due to the thread execution sequence, but the first thread 2 is starting in doubt, it should be thread 0 is starting, to be resolved)
[Email protected]:/mnt/hgfs/source test/file io$ gcc thread_mutex.c-lpthread-d_reentrant
thread_mutex.c:in function ' Thrd_func ':
Thread_mutex.c:14:warning:cast from pointer to integer of different size
thread_mutex.c:in function ' main ':
Thread_mutex.c:58:warning:cast to pointer from integer of different size
[Email Protected]:/mnt/hgfs/source test/file io$./a.out
Create Treates Success
Waiting for threads to finish ...
Thread 2 is starting
Thread 2:job 0 delay = 3
Thread 2:job 1 delay = 3
Thread 2:job 2 delay = 1
Thread 2 finished
Thread 1 is starting
Thread 1:job 0 delay = 1
Thread 1:job 1 delay = 1
Thread 1:job 2 delay = 1
Thread 1 finished
Thread 0 is starting
Thread 0:job 0 delay = 3
Thread 0:job 1 delay = 3
Thread 0:job 2 delay = 2
Thread 0 finished
Thread 0 joined
Thread 1 joined
Thread 2 joined
[Email Protected]:/mnt/hgfs/source test/file io$

*************************************************************************************************************** ************************************************
*************************************************************************************************************** ************************************************
*************************************************************************************************************** ************************************************
*************************************************************************************************************** ************************************************

exec function family, daemon, thread synchronization and mutex

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.