实验一:进程和线程的创建
1. 在linux下编写一个应用程序,命名为an_ch2_1b。这个程序不断地输出如下行:
Those output come from child,[系统时间]
另外写一个应用程序,命名为an_ch2_1a。这个程序创建一个子进程,执行an_ch2_1b。这个程序不断地输出如下行:
Those output come from child,[系统时间]
观察程序运行的结果,并对你看到的现象进行解释。
这个是an_ch2_1a.cpp
#include <iostream>
#include <unistd.h>
#include <cstdio>
#include <sys/types.h>
#include <stdlib.h>
using namespace std;
int main()
{
time_t now;
tm * timenow;
pid_t pid;
pid = fork();
if(pid==-1){
cout<<"fail to create"<<endl;
}
else if(pid==0){
system("./an_ch2_1b");
}
}
写完之后保存,命令行输入:g++ -o aaa an_ch2_1a.cpp
进行编译。生成可执行文件aaa。
这个是an_ch2_1b.cpp
#include <iostream>
#include <cstdio>
#include <sys/types.h>
#include <unistd.h>
#include <time.h>
using namespace std;
int main()
{
time_t now;
tm * timenow;
while(true){
time(&now);
timenow = localtime(&now);
cout<<"Those output come from child,"<<asctime(timenow)<<endl;
}
}
写完之后保存,命令行输入:g++ -o an_ch2_1b an_ch2_1b.cpp
进行编译。生成可执行文件an_ch2_1b
<pre name="code" class="cpp"><pre name="code" class="cpp">在命令行输入:./an_ch2_1b
执行an_ch2_1b
在命令行输入:./aaa 执行aaa
kill掉当前进程是ctrl+c
2.
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
int share_var=0;
void * son(void * arg)
{
while(1){
share_var--;
printf("in the son share_var:%d\n",share_var);
usleep(1000);
}
}
int main()
{
pthread_t pt;
int ret;
ret=pthread_create(&pt,NULL,(void*)son,NULL);
if(ret!=0){
printf("create fail\n");
}
while(1){
share_var++;
printf("in the main shaer-var:%d\n",share_var);
usleep(1000);
}
pthread_join(pt,NULL);
}