开发环境:VirtualBox 版本 6.1.26 Ubuntu版本 16.04.7 codeBlocks版本13.04
代码如下:
#include <stdio.h>#include <string.h>#include <stdlib.h>int count1=0;int main(void){ int fpid; int pid; int nap; srand(time(NULL)); int count2=0; int i,j; char name[10]=""; count1++; count2++; fpid=fork(); pid = getpid(); for(i=1;i<=15;i++)for(j=1;j<=20;j++){if(fpid){strcpy(name,"father"); nap=rand()%2; sleep(nap);}else{ strcpy(name,"child"); nap=rand()%2; sleep(nap);}printf("%s pid = %d: count1= %d count2=%d
" ,name,pid, count1++,count2++);}if(fpid) wait();//阻塞父进程至子进程完成后执行return 0;}
会出现如下报错:
这时,如果我们加上这两个库
#include <pthread.h>#include <unistd.h>
会发现可能仍然会出现报错。
这时我们需要点击CodeBlocks中project-Build options
选择Linker settings,在Other linker options中输入
-lpthread
此时,虚拟机下的CodeBlocks就可以正常运行多线程编程程序了。
希望本文可以帮助到大家!!