Linux——进程练习

发布于:2024-06-28 ⋅ 阅读:(47) ⋅ 点赞:(0)

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;
}


网站公告

今日签到

点亮在社区的每一天
去签到