5.6作业

/*使用文件IO函数,拷贝一张图片,
父进程拷贝前半部分,子进程拷贝后半部分。
不能使用sleep函数。
提示:
一个进程拷贝完毕后再开始另外一个进程。
父子进程各自开各自的文件。*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main() {
    pid_t pid;
    int status;
    FILE *src_file, *dst_file;
    char ch;
    int i = 0;

    src_file = fopen("original.jpg","rb");
    if (src_file == NULL) {
        printf("Failed to open the file!\n");
        exit(-1);
    }

    dst_file = fopen("copy.jpg", "wb");
    if (dst_file == NULL) {
        printf("Failed to create the new file!\n");
        fclose(src_file);
        exit(-1);
    }

    pid = fork();
    if (pid == 0) { // child process
        while(fread(&ch,sizeof(char),1,src_file)) {
            if (i >= 1024) {
                fwrite(&ch,sizeof(char),1,dst_file);
            }
            i++;
        }
        printf("Child process ends.\n");
        exit(0);
    }
    else { // parent process
        while(fread(&ch,sizeof(char),1,src_file)) {
            if (i < 1024) {
                fwrite(&ch,sizeof(char),1,dst_file);
            }
            i++;
        }
        wait(&status);
        printf("Parent process ends, child status: %d\n", status);
    }

    fclose(src_file);
    fclose(dst_file);

    return 0;
}
//验证运行到waitpid非阻塞形式时,若子进程没退出,则子进程会不会变成僵尸进程
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int main() {
    pid_t pid;
    int status;

    pid = fork();

    if (pid == 0) {
        // 子进程
        printf("child process\n");
        sleep(10);
        printf("child process exit\n");
    } else if (pid > 0) {
        // 父进程
        printf("parent process\n");
        while (1) {
            if (waitpid(pid, &status, WNOHANG) == pid) {
                printf("child process exit status:%d\n", status);
                break;
            }
            printf("parent process working\n");
            sleep(1);
        }
    } else {
        // fork失败
        printf("fork error\n");
    }

    return 0;
}
创建孤儿进程:
```c
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

int main() {
  pid_t pid = fork();
  if(pid == -1) {
    printf("error");
  } else if(pid == 0) {
    sleep(10); // 子进程睡眠10秒
  } else {
    exit(0); // 父进程退出
  }
  return 0;
}
创建僵尸进程:
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

int main() {
  pid_t pid = fork();
  if(pid == -1) {
    printf("error");
  } else if(pid == 0) {
    printf("I'm child process, pid=%d\n", getpid());
    exit(0); // 子进程立即退出
  } else {
    printf("I'm parent process, pid=%d\n", getpid());
    sleep(10); // 父进程睡眠10秒
  }
  return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值