欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 产业 > Linux——进程练习

Linux——进程练习

2024/10/24 12:27:42 来源:https://blog.csdn.net/m0_71703182/article/details/140003942  浏览:    关键词:Linux——进程练习

1、使用进程知识点,尝试完成如下功能:

输入n, 动态生成n个子进程,并打印输出各自进程的pid号。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>#include <sys/types.h>int main(int argc, char *argv[])
{int n =3;int i = 0 ;for(i=0;i<n;i++){pid_t pid = fork();if(pid>0){continue;}else if(0 == pid){printf("child, pid:%d ppid:%d\n",getpid(),getppid());exit(0);}else {perror("fork");return 1;}}printf("father pid:%d, ppid:%d\n",getpid(),getppid());return 0;
}

2、设计一个程序,动态生成两个进程,分别向相同的文件中写入不同的数据,要表明是两个进程同时写入的数据。
./a.out ===> 1.txt ==>父进程写入的信息 时间+编号(father pid)/a.out时间+编号(child pid)父进程1123 186 16:02:10子进程1124 188 16:02:15

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>#include <sys/types.h>
#include <time.h>
#include <dirent.h>
int do_count()
{DIR* dir = opendir("/proc");if(NULL == dir){perror("opendir");exit(1);}int num=0;while(1){struct dirent* info = readdir(dir);if(NULL == info){break;}if(DT_DIR == info->d_type  ){if(info->d_name[0]>'0' && info->d_name[0]<'9'){num++;}}else{continue;}}closedir(dir);return num;
}
int main(int argc, char *argv[])
{FILE* fp = fopen("1.txt","w");if(NULL == fp){perror("fopen");exit(1);}time_t tm;int n = 3;pid_t pid = fork();if(pid>0){while(n--){int num=do_count();time(&tm);fprintf(fp,"father %d %d %s",getpid(),num,ctime(&tm));fflush(fp);sleep(3);}}else if(0 == pid){while(n--){int num=do_count();time(&tm);fprintf(fp,"child %d %d %s",getpid(),num,ctime(&tm));fflush(fp);sleep(5);}}else {perror("fork");return 1;}fclose(fp);return 0;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com