Network programming experiment

1, create two new programming process, each new process is responsible for printing out:

(1) "Hello! My father is + parent process ID"

(2) "I am + the child process number"

(3) within 50 primes

2, programming to create three new threads, each thread requires new parameters obtained from the main thread, and is responsible for printing out:

(1) "Hello! My father is + parent process ID"

(2) "I am + the child process number"

(3) determining whether the parameter is a prime number


 

code show as below

multi-Progress

#include <stdio.h>
#include <unistd.h>
#include <math.h>
int main(){
        int t;

    for (T = 0 ; T <= . 1 ; T ++ ) {
         int RET = the fork (); // create a new process 
       SLEEP ( . 3 );
         IF (RET == 0 ) {
       // output resolution parent process, the child process number         
    printf ( " ! My Father the Hello% D IS, D the I AM% \ n- " , getppid (), getpid ());

// output within 50 prime 
    int I, n-;
     for (I = 2 ; I <= 50 ; I ++ ) within
    {
    for(n=2;n<=(int)sqrt(i);n++)
    if(i%n==0)break;
    if(n==(int)sqrt(i)+1)
    printf("%d  ",i); }
       printf("\n");
    exit(1);
        }
    if(ret==-1){
         perror("fork error!");
        }
        } 
     for(t=0;t<=1;t++){wait(NULL);
    }
   
    return 0;
}

 

 


 

Multi-threaded code

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/syscall.h>
void *thread(void * arg)
{   
    int pid,n;pid=(int)arg;
    printf ( " the Hello, My Father the I AM IS% d% LU,!! " , getpid (), pthread_self ());   // output process ID, the child process ID

// the syscall (SYS_gettid) 
    for (n-= 2 ; n-<PID; n-++)     // check whether it is a prime 
    {
         IF (PID% n-== 0 ) { BREAK ;}
    }
    if(n==pid){
    printf("%d is shushu\n",pid);}
    else {
    printf("%d is not shushu\n",pid);}
    the pthread_exit ( 0 );    // after cleanup 
}
      
int main ()
{
    pthread_t tid[3];int n=13;int i;
    for(i=0;i<3;i++)
    {
    int RET = pthread_create (& TID [I], NULL, Thread, ( void *) n-); // Create a thread
   
    if(ret)printf("create thread failed! ret:%d\n",ret);
    }
     for(i=0;i<3;i++)      
    usleep(1);
    for(i=0;i<3;i++)
    pthread_join (TID [I], NULL);    // wait for the end of the thread
   
    return 0;
}

 

Multi-process successfully run shot

 

Multithreading successfully run shot

  I was a novice small code slag, this is purely for practice use, if ill-please forgive!

 

Guess you like

Origin www.cnblogs.com/Ada-Yxd/p/12006826.html