编程解决问题:
1号进程创建2,3号两个进程
2号进程创建两个线程Thread1,Thread2
Thread1:求(1~n)之间的素数
Thread2:生成Fibonacci序列
3号进程创建4,5号两个进程
4号进程执行系统命令,ls,ps,cp等
5号进程执行一个用户编写的可执行文件
每个进程输出自己的进程ID和父进程的进程ID
/*
* OSPro1.c
*
* Created on: Nov 10, 2016
* Author: koala
*/
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/wait.h>
#include<stdlib.h>
#include<pthread.h>
//Fibonacci sequence
void Fibonacci()
{
int f[100]={0};
f[0] = 0;
f[1] = 1;
printf("Fibonacci sequence is: ");
int a;
for(a=2;a<10;a++)
{
f[a]= f[a-1] + f[a-2];
}
for(a=0;a<10;a++)
printf("%d ",f[a]);
printf("\n");
printf("Thread Fibonacci exit\n");
pthread_exit(0);
}
//Primenumber sequence
void Primenumber(void*arg)
{
int n = *(int *)arg;
int i;
int j;
int flag;
printf("Primenumber sequence is: %d ",2);
for(i=2; i<=n; i++)
{
for(j=2; j<i; j++)
{
if(i%j == 0){
flag =0;
break;
}
flag =1;
}
if(flag)
printf("%d ",i);
}
printf("\n");
printf("Thread Primenumber exit\n");
pthread_exit(0);
}
int main()
{
pid_t pid_1, pid_2, pid_3; //Declare 3 process
pid_1 = getpid();
printf("Parent Pid_1 is %d\n", pid_1);
if((pid_2 = fork()) == 0) //fork() create children process
{
int ret1, ret2;
pthread_t tid1, tid2; //Declare 2 thread
printf("Pid_2 is %d, its parent is %d\n", getpid(), getppid());
int n=20;
ret1 = pthread_create(&tid1, NULL, (void*)Primenumber, &n); //create thread and execute Primenumber()
if(ret1 == 0)
printf("Thread_1 ok!\n");
else
printf("Thread_1 failed!\n");
ret2 = pthread_create(&tid2, NULL, (void*)Fibonacci, NULL);//create thread and execute Fibonacci()
if(ret2 == 0)
printf("Thread_2 ok!\n");
else
printf("Thread_2 failed!\n");
pthread_join(tid1, NULL);//waitting thread1 finished
pthread_join(tid2, NULL);//waitting thread2 finished
}
if((pid_3 = fork()) == 0 && getppid() == pid_1)
{
pid_t pid_4, pid_5;
printf("Pid_3 is %d, its parent is %d\n", getpid(), getppid());
if((pid_4 =fork()) == 0)
{
printf("Pid_4 is %d, its parent is %d\n", getpid(), getppid());
int ret3;
ret3 = execl("/bin/ls", "ls", "-l", NULL);
if(ret3 < 0)
perror("execl error!\n");
else printf("Successfuly execute the ls -l commond!\n");
}
if((pid_5 = fork()) == 0)
{
printf("Pid_5 is %d, its parent is %d", getpid(), getppid());
int ret4;
ret4 = execl("demo", "./demo", NULL);//execute demo.c (./demo)
if(ret4 < 0)
perror("execl error!\n");
else
printf("Successfuly execute the \"demo\"!\n");
}
pid_t cpid = wait(NULL);
printf("The process 3 exit, and its child process is %d\n", cpid);
}
pid_t cpid = wait(NULL); //waitting children process finished
printf("The process %d exit\n", cpid);
exit(0);
return 0;
}
//demo.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("This is \"demo\" process !\n");
return 0;
}
运行效果: