fork函数小东西

    刚开始学进程、看到例程就自己也想到了一个,敲出来后运行下、和预想的一样;

    除了书本没有什么师傅的弱菜忍不住赶紧来卖弄一下,上代码:



子进程负责随机生成100个字符;

父进程负责将这100个字符重新输出到另外一个文件中、同时将其中的小写字符变成大写字符:

#include"sys/types.h"
#include"sys/wait.h"
#include"unistd.h"
#include"stdio.h"
#include"stdlib.h"
#include"math.h"


int main()
{
	pid_t pid;
	char *message;
	int exit_code;

	printf("fork program starting\n");
	pid = fork();

	if(pid != 0 && pid != -1){
		int stat_val;
		pid_t child_pid;

		child_pid = wait(&stat_val);

		printf("Child has finished: PID = %d\n", child_pid);
		if(WIFEXITED(stat_val))
			printf("Child has finished: PID = %d\n", WEXITSTATUS(stat_val));
		else
			printf("Child terminated abnormally\n");
	}

	if(pid == -1){
		perror("fork failed");
		exit(1);
	}
	else if(!pid){
		int i,temp;
		FILE *write;

		srand((int)time(0));
		write = fopen("/home/hello/c++_test/hehe", "w");

		for(i = 0; i < 100; i++){
			temp = abs( rand() ) % 127;
			fprintf(write, "%c", temp);
		}
		(void)fclose(write);

		exit_code = 36;
	}
	else{
		int i;
		char ch;
		FILE *input, *output;

		input = fopen("/home/hello/c++_test/hehe", "r");
		output = fopen("/home/hello/c++_test/hehe2", "w");

		while((ch = fgetc(input)) != EOF){
			if('a' <= ch && ch <= 'z')	ch-=32;
			fprintf(output, "%c", ch);
		}

		(void)fclose(input);
		(void)fclose(output);

		exit_code = 0;
		printf("ok~\n");
	}

	exit(exit_code);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值