#include <unistd.h>
#include <stdio.h>
int main ()
{
pid_t pids,pidd; //pid表示fork函数返回的值
while((pids=fork())==-1);
if (pids == 0) { //在子进程中,fork返回0
printf("i am son\n");
return 0;
}
else{
while((pidd=fork())==-1);
if (pidd == 0) { //在子进程中,fork返回0
printf("i am daughter\n");
return 0;
}
else {//在父进程中,fork返回新创建子进程的进程ID
printf("i am father\n");
}
}
return 0;
}
//3_3
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
int main(){
pid_t pid;
if((pid=fork())==0){
printf("I am son\n");
exit(0);
}
else if(pid>0){
wait(0);
if((pid=fork())==0){
printf("I am daughter\n");
exit(0);
}
else if(pid>0){
wait(0);
printf("I am father\n");
exit(0);
}
}
return 0;
}
//3_4_1
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
int main(){
pid_t pid;
while((pid=fork())==-1);
if(pid==0){//child
execl("/bin/ls","ls","-l",NULL);
exit(0);
}
else{
wait(0);
exit(0);
}
return 0;
}
//3_4_2
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
int main(){
pid_t pid;
while((pid=fork())==-1);
if(pid==0){//child
execl("./child2",0);
exit(0);
}
else{
wait(0);
exit(0);
}
return 0;
}
//child2
#include <unistd.h>
#include <stdio.h>
int main(){
printf("I am child2 file\n");
return 0;
}
//4_2
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#define MAX 100
int main()
{
pid_t pid;
int fd[2];
char W[MAX];
char R[MAX];
if(pipe(fd)<0)
{
perror("Error occured in pipe");
exit(1);
}
if((pid=fork())<0)
{
perror("Error occured in fork");
exit(1);
}
else
{
if(pid==0)
{//child
strcpy(W,"is sending a message to parent!\n");
write(fd[1],W,sizeof(W));
close(fd[0]);
close(fd[1]);
}
else
{//parent
close(fd[1]);
read(fd[0],R,sizeof(R));
printf("%s",R);
close(fd[0]);
}
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void swap(int *x,int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
int choose_pivot(int i,int j )
{
return((i+j) /2);
}
void quicksort(int list[],int m,int n)
{
int key,i,j,k;
if( m < n)
{
k = choose_pivot(m,n);
swap(&list[m],&list[k]);
key = list[m];
i = m+1;
j = n;
while(i <= j)
{
while((i <= n) && (list[i] <= key))
i++;
while((j >= m) && (list[j] > key))
j--;
if( i < j)
swap(&list[i],&list[j]);
}
// 交换两个元素的位置
swap(&list[m],&list[j]);
// 递归地对较小的数据序列进行排序
quicksort(list,m,j-1);
quicksort(list,j+1,n);
}
}
void printlist(int list[],int n)
{
int i;
for(i=0;i<n;i++)
printf("%d\t",list[i]);
}
int main()
{
const int MAX_ELEMENTS = 10;
int list[MAX_ELEMENTS];
srand((int)time(0));
int i = 0;
// 产生填充序列的随机数
for(i = 0; i < MAX_ELEMENTS; i++ ){
list[i] = rand()%100-50;
}
printf("进行排序之前的序列:\n");
printlist(list,MAX_ELEMENTS);
// sort the list using quicksort
quicksort(list,0,MAX_ELEMENTS-1);
// print the result
printf("使用快速排序算法进行排序之后的序列:\n");
printlist(list,MAX_ELEMENTS);
return 0;
}