#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<unistd.h>
#include<sys/wait.h>
typedef struct _list
{
struct _list *next;
int _val;
}product_list;
product_list *head = NULL;
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t need_product = PTHREAD_COND_INITIALIZER;
void Init_list(product_list* list)
{
if(list != NULL)
{
list -> next = NULL;
list -> _val = 0;
}
}
void* Consumer(void* _val)
{
product_list *p = NULL;
for(;;)
{
pthread_mutex_lock(&lock);
while(head == NULL)
{
pthread_cond_wait(&need_product,&lock);
}
p = head;
head = head -> next;
p -> next = NULL;
pthread_mutex_unlock(&lock);
printf("Consum success,val is:%d
",p -> _val);
free(p);
}
return NULL;
}
void* Product(void* _val)
{
for(;;)
{
sleep(rand() % 2);
product_list* p =malloc(sizeof(product_list));
pthread_mutex_lock(&lock);
Init_list(p);
p -> _val = rand() % 1000;
p -> next = head;
head = p;
pthread_mutex_unlock(&lock);
printf("Call consumer! Product has producted,val is:%d
",p->_val);
pthread_cond_signal(&need_product);
}
}
int main()
{
pthread_t t_product;
pthread_t t_consumer;
pthread_create(&t_product,NULL,Product,NULL);
pthread_create(&t_consumer,NULL,Consumer,NULL);
pthread_join(t_product,NULL);
pthread_join(t_consumer,NULL);
return 0;
}
实验三
进程的终止与等待,
参考《Linux操作系统基础、原理与应用(第2版)》p107例5-4,
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
int main()
{
int rid, cid, status;
rid = fork();
if ( rid < 0 ) { printf(“fork error!”; exit(1); }
if ( rid > 0 ) { printf(“Child: I will exit in 10 seconds. ”);
sleep(10);
exit(0);
}
cid=wait(&status);
printf(“Parent: I caught a child with PID of %d. ”, cid);
if ((status & 0377) == 0)
printf(“It exited normally, with status of %d. ”, status>>8);
else printf(“It was terminated by signal %d. ”, status&0177);
exit(0);
}
实验四
用fork()、exec()和wait()系统调用写一个简单的测试程序。父进程创建一个子进程,执行date命令。子进程结束后,父进程输出子进程的PID和退出码
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
int main()
{
int rid, cid, status;
rid = fork();
if ( rid < 0 ) { printf(“fork error!”; exit(1); }
if ( rid > 0 ) { execlp(“date”, “date”, NULL);
exit(0);
}
cid=wait(&status);
printf(“Parent: I caught a child with PID of %d. ”, cid);
if ((status & 0377) == 0)
printf(“It exited normally, with status of %d. ”, status>>8);
else printf(“It was terminated by signal %d. ”, status&0177);
exit(0);
}