プロセスとスレッドの簡単な実験

[実験要件]:

  fork関数、exec関数、pthread関数の使用方法を学び、ソースコードを読んで、3つの関数のメカニズムを分析します。

[コードの実装]:

  プロセスAは子プロセスBを作成します

  プロセスAはhello worldを出力し、プロセスBはSum累積を実装します

  プロセスBには2つのスレッドがあり、メインスレッドはSum累積を達成するためにサブスレッドを作成します

各エグゼクティブのプロセッサ使用量やメモリ使用量などの基本情報の分析

 

【分析】

これを書くには、最初にfork exec pthread関数を見てください!

いくつかのブログが参考になります

https://www.cnblogs.com/amanlikethis/p/5537175.html

https://blog.csdn.net/nan_lei/article/details/81636473

https://blog.csdn.net/u011279649/article/details/18736181

これを読んだら、基本的には書き始めることができます

ソースコードは非常にシンプルで、2つのファイル、1つの処理スレッドと1つの作成プロセスBに分かれています。

プロセスのmain.cを処理する

1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <pthread.h>
 4 #include <unistd.h>
 5 #include <sys / types.h>
 6 #include <wait.h>
 7  
8  int main(){
 9      pid_t pid;
10      pid = fork();
11      // 父と子を分ける
12      if(pid < 0 ){
 13          printf(" Fork failed \ n " );
14          exit(-1 );
15      }
 16 
17      else  if(pid == 0 ){
 18          printf(" これは子pid =%dです。\ n " 、getpid());
19          // exec 
20          char * buf [] = { " / home / ying / experi-os / child "" child "、NULL}; // bのパス。
21          execve(" / home / ying / experi-os / child " 、buf、NULL);
22      }
 23  
24      else {
 25          printf(" Hello world!Father pid is%d。\ n" )GETPID();
 26          // そして(B)完成子を待つ。
27          ウェイト(NULL);
 28          出口(0 );
 29      }
 30 }

スレッドを処理するchild.cもあります

1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <pthread.h>
 4 #include <unistd.h>
 5  
6  int x = 0、sum = 0 ;
7  
8  void * Sum(void * arg){
 9      // printf( "sum begin successful!\ n"); 
10      forint i = 1 ; i <= x; i ++ ){
 11          sum + = i;
12      }
 13      printf(" \ n結果は%dです\ n "、合計);
14  }
 15  
16  int main()
 17  {
 18      printf(" exec success。\ nInput x:" );
19      if(scanf(" %d "、&​​x)!= 1 ){
 20          return  0 ;
21      }
 22  
23      pthread_t id;
24      pthread_create(&id、NULL、Sum、(void * )NULL);
25      pthread_join(id、NULL); // スレッドの終了を待つ
26  
27      exit(0);
28は     0を返し ます29 }

次にそれらを個別にコンパイルます

1 gcc child.c -o child- lpthread
 2 gcc mian.c -o main

実行は

1 ./メイン

現時点では、-lpthreadをスレッドのコンパイルに追加する必要があることに注意する必要があります。Linuxにはデフォルトのライブラリがないようです。

 

 

 

 以上です!

 

【バグまとめ】

書き込みプロセス中にいくつかのエラーがありました

1.合計機能がエラーを報告します。Sum関数は、スレッドの仮パラメーター要件に応じた*合計でなければなりません。

2.メインは定義を繰り返します。2つのファイルがリンクコンパイルではなく、execve命令によってリンクされている

3. child.cのコンパイル時にスレッドエラーが報告されます。その理由は、-lpthreadが追加されていないためです。

4.ランタイムのバグ。execveが正しいスレッド実行可能ファイルを指していないため

上記の点は基本的にこの実験では問題ないことに注意してください、それは本当に簡単です

おすすめ

転載: www.cnblogs.com/jhjgarden/p/12683459.html