【Linux之路】进程与线程(实验)

实验1.  创建俩个进程, 让子进程读取一个文件, 父进程等待子进程读完文件后继续执行

相关代码:

#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>

int main () 
{
  pid_t pc;
  pc = fork();
  if (pc < 0) 
    printf("new error");
  else if (pc == 0) {
    printf("here in child thread\n");
    FILE *fp;
    fp=fopen("123.456","w+");
    if(fp != NULL){
      fprintf(fp, "打开文件成功");
      fclose(fp);
    } else
      printf("打开文件成败");
    exit (3);
  } else {
    wait(&pc);
    printf("   here in parent thread\n");
  }
  return 0;
}

实验2, 线程共享进程中的数据, 在进程中直接引用并输出该数据:

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
static int shdata = 4;

void*create(void*arg) 
{
  printf("new pthread....\n");
  printf("shared data =%d \n", shdata);
  return (void*)0;
}

int main (int argc, char* argv[])
{
  pthread_t tidp;
  int error;
  error = pthread_create(&tidp, NULL, create, NULL);
  if (error != 0) 
  {
     printf("failed to create thread");
     return -1;
  }
  printf("before sleep\n");
  sleep(1);
  printf("success to create thread\n");
  return 0;
}

zheng@zheng-ThinkPad-Edge-E430:~/test/thread$ ./a.out
before sleep
new pthread....
shared data =4
success to create thread
zheng@zheng-ThinkPad-Edge-E430:~/test/thread$


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值