目录
Linux创建、编译文件
命令行touch 文件.后缀,创建源文件
如:touch demo.cpp创建cpp源文件
编译cpp源文件,gcc 文件名,后缀 -o 目标文件
如:gcc demo.cpp -o a
Linux未找到unistd.h头文件
在编辑的cpp当前文件夹下,创建一个unistd.h头文件,输入以下代码即可。
#ifndef _UNISTD_H
#define _UNISTD_H
#include <io.h>
#include <process.h>
#endif /* _UNISTD_H *
进程创建
Linux下,创建进程,需要使用unisted.h头文件。
fork()会创建一个新的进程,分别返回父子两个进程的PID,因此检测两次即可。
#include<unistd.h>
#include<stdio.h>
#include<sys/wait.h>
const int num = 100;
int main(){
int rc = fork();
if(rc < 0){
printf("Fork failed!\n");
}else if(rc == 0){//输出偶数
for(int i = 0; i <= num; i += 2){
printf("Child process:%d\t\n", i);
sleep(1);
}
}else{//输出奇数
for(int i = 1; i <= num; i += 2){
printf("Parent process:%d\n", i);
sleep(1);
}
}
return 0;
}
//liqiang
//SIAT100051
线程创建
Linux下,创建进程,需要使用pthread.h头文件。
sleep()需要包含unisted.h头文件
pthread是线程库,用了多线程就要链接这个库,这时候要在编译选项上增加-pthread
编译多线程:gcc thread.cpp -o thread -pthread
#include<unistd.h>
#include<stdio.h>
#include<pthread.h>
void *ThreadF(void* arg){
printf("\nI'm child thread. My pid is %lu\nI will print number between 0 to 100",(unsigned long)pthread_self());
for(int i=0; i < 100;i+=2){
printf("%d\t",i);
}
}
int main(){
pthread_t p;
pthread_create(&p,NULL,ThreadF,(void*)100);
printf("\nI'm parent thread. My pid is %lu\nI will print number between 0 to 100\n",(unsigned long)pthread_self());
for(int i=1; i < 100;i+=2){
printf("%d\t",i);
}
sleep(1);
return 0;
}