c - 如何从 PROC 获取有关子进程的信息

标签 c linux process child-process

我正在尝试编写一个以几个进程作为参数的程序。然后父进程执行每个子进程并打印出一些关于子进程的统计信息。

示例:/generate ls -l//Would result in a program that prints输出一些关于 ls -l 的统计数据(特别是它的系统时间、用户时间和上下文切换次数)。

我不想使用 getrusage() 函数,而是想从进程文件系统。现在我的理解是,如果我要使用 wait() 函数,它最终会从我的 proc 文件系统中删除信息。我在下面包含了我的代码

#include <time.h>
#include <stdbool.h>
#include <assert.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/resource.h>



void inputted_command(int a, char **b){
 for(int i=1;i<a;i++)
     printf("%s ",b[i]);


}

int main(int argc, char **argv){
    int status; 
  pid_t childpid;
  pid_t get_information;
if (argc < 2)
    {

        return 1;
    }

    bool handle_signals = (signal(SIGINT, SIG_IGN) != SIG_IGN); 
    clock_t t; 
    t= clock(); 
    pid_t pid = fork();

if(pid<0) 
{
printf("fork: error no = %s\n",strerror(errno));
 return 1;

}
else if(pid>0){
    signal(SIGINT,SIG_IGN); 

  sleep(60);

  /*
   get_information=fork();
   if(get_information==0){
     execlp(___);

   }else
  waitpid(pid, &status, 0); 



  */
  waitpid(childpid, &status, 0); 

    t= clock()-t; 
    double real_time_taken = ((double)t)/CLOCKS_PER_SEC;

  printf("The command "); 
  inputted_command(argc,argv);
  if(WIFSIGNALED(status)){

  printf("is interrupted by the signal number = %d (Insert Name Here) real: %.2f, user: , system: , context switch:  \n",WTERMSIG(status),real_time_taken);

}

else{

printf("terminated with return status code = %d real: %.2f, user: , system: , context switch:  \n",WEXITSTATUS(status), real_time_taken);

}

}

else if(pid==0){
       childpid=getpid();
        printf("Process with id: %d created for the command: ",(int)getpid());
        inputted_command(argc,argv);
        printf("\n");
        assert(pid == 0); 
        if (handle_signals) 
        signal(SIGINT, SIG_DFL);
        execvp(argv[1], &argv[1]); 
        printf(" experienced an error in starting the command: ");
        inputted_command(argc,argv);
        printf("\n");
        exit(-1);
      }

}

  • 我的部分代码已被注释,我不确定该怎么做。
  • 我的想法是首先让父进程进入休眠状态,以便子进程完成终止。
  • 然后父进程创建一个新的子进程来访问 PROC/Fie 系统并获取必要的数据(已评论) .
  • 最后,我再次调用等待函数并终止初始子进程

所以我这里的主要问题是这是否是获得子进程的信息以及如何获取信息(主要是系统时间、用户时间以及自愿和非自愿的上下文切换?

最佳答案

这是我编写的一个测试程序,它可能会提供一些启示(警告:它有些粗糙):

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>

int mode = -1;
pid_t pid;
time_t cur;
FILE *xf;
char dirproc[100];
char dirfd[100];
char status_file[100];
char cmd[100];

void
xsystem(char *cmd)
{

    printf("CMD: %s\n",cmd);
    system(cmd);
}

int
check(int nmode)
{
    struct stat st;
    int errst;
    int errkill;
    char buf[500];

    errkill = kill(pid,0);
    errst = stat(dirproc,&st);

    if (nmode != mode) {
        printf("elap=%d errkill=%d errst=%d\n",cur,errkill,errst);

        sprintf(cmd,"ls -l /proc/%d",pid);
        xsystem(cmd);

        sprintf(cmd,"ls -l /proc/%d/fd",pid);
        xsystem(cmd);

        sprintf(cmd,"cat /proc/%d/status",pid);
        xsystem(cmd);

        printf("fgets\n");

        rewind(xf);
        while (1) {
            char *cp = fgets(buf,sizeof(buf),xf);
            if (cp == NULL)
                break;
            fputs(buf,stdout);
        }

        mode = nmode;
    }

    return errkill;
}

// main -- main program
int
main(int argc,char **argv)
{
    char *cp;

    --argc;
    ++argv;

    for (;  argc > 0;  --argc, ++argv) {
        cp = *argv;
        if (*cp != '-')
            break;

        switch (cp[1]) {
        default:
            break;
        }
    }

    setlinebuf(stdout);
    setlinebuf(stderr);

    pid = fork();

    if (pid == 0) {
        open("/dev/null",O_RDONLY);
        sleep(1);
        exit(0);
    }

    sprintf(dirproc,"/proc/%d",pid);
    sprintf(dirfd,"/proc/%d/fd",pid);
    sprintf(status_file,"/proc/%d/status",pid);
    xf = fopen(status_file,"r");

    time_t beg = time(NULL);
    cur = 0;

    while (1) {
        cur = time(NULL);

        cur -= beg;
        if (cur >= 4)
            break;

        check(1);
    }

    printf("\n");
    printf("postloop\n");
    check(2);

    waitpid(pid,NULL,0);
    printf("\n");
    printf("postwait\n");
    check(3);

    return 0;
}

程序输出如下:

elap=0 errkill=0 errst=0
CMD: ls -l /proc/94913
total 0
dr-xr-xr-x. 2 xxx xxx 0 Oct 21 15:50 attr
-rw-r--r--. 1 xxx xxx 0 Oct 21 15:50 autogroup
-r--------. 1 xxx xxx 0 Oct 21 15:50 auxv
-r--r--r--. 1 xxx xxx 0 Oct 21 15:50 cgroup
--w-------. 1 xxx xxx 0 Oct 21 15:50 clear_refs
-r--r--r--. 1 xxx xxx 0 Oct 21 15:50 cmdline
-rw-r--r--. 1 xxx xxx 0 Oct 21 15:50 comm
-rw-r--r--. 1 xxx xxx 0 Oct 21 15:50 coredump_filter
-r--r--r--. 1 xxx xxx 0 Oct 21 15:50 cpuset
lrwxrwxrwx. 1 xxx xxx 0 Oct 21 15:50 cwd -> /tmp/cld
-r--------. 1 xxx xxx 0 Oct 21 15:50 environ
lrwxrwxrwx. 1 xxx xxx 0 Oct 21 15:50 exe -> /tmp/cld/pgm2
dr-x------. 2 xxx xxx 0 Oct 21 15:50 fd
dr-x------. 2 xxx xxx 0 Oct 21 15:50 fdinfo
-rw-r--r--. 1 xxx xxx 0 Oct 21 15:50 gid_map
-r--------. 1 xxx xxx 0 Oct 21 15:50 io
-r--r--r--. 1 xxx xxx 0 Oct 21 15:50 latency
-r--r--r--. 1 xxx xxx 0 Oct 21 15:50 limits
-rw-r--r--. 1 xxx xxx 0 Oct 21 15:50 loginuid
dr-x------. 2 xxx xxx 0 Oct 21 15:50 map_files
-r--r--r--. 1 xxx xxx 0 Oct 21 15:50 maps
-rw-------. 1 xxx xxx 0 Oct 21 15:50 mem
-r--r--r--. 1 xxx xxx 0 Oct 21 15:50 mountinfo
-r--r--r--. 1 xxx xxx 0 Oct 21 15:50 mounts
-r--------. 1 xxx xxx 0 Oct 21 15:50 mountstats
dr-xr-xr-x. 6 xxx xxx 0 Oct 21 15:50 net
dr-x--x--x. 2 xxx xxx 0 Oct 21 15:50 ns
-r--r--r--. 1 xxx xxx 0 Oct 21 15:50 numa_maps
-rw-r--r--. 1 xxx xxx 0 Oct 21 15:50 oom_adj
-r--r--r--. 1 xxx xxx 0 Oct 21 15:50 oom_score
-rw-r--r--. 1 xxx xxx 0 Oct 21 15:50 oom_score_adj
-r--------. 1 xxx xxx 0 Oct 21 15:50 pagemap
-r--------. 1 xxx xxx 0 Oct 21 15:50 personality
-rw-r--r--. 1 xxx xxx 0 Oct 21 15:50 projid_map
lrwxrwxrwx. 1 xxx xxx 0 Oct 21 15:50 root -> /
-rw-r--r--. 1 xxx xxx 0 Oct 21 15:50 sched
-r--r--r--. 1 xxx xxx 0 Oct 21 15:50 schedstat
-r--r--r--. 1 xxx xxx 0 Oct 21 15:50 sessionid
-rw-r--r--. 1 xxx xxx 0 Oct 21 15:50 setgroups
-r--r--r--. 1 xxx xxx 0 Oct 21 15:50 smaps
-r--r--r--. 1 xxx xxx 0 Oct 21 15:50 smaps_rollup
-r--------. 1 xxx xxx 0 Oct 21 15:50 stack
-r--r--r--. 1 xxx xxx 0 Oct 21 15:50 stat
-r--r--r--. 1 xxx xxx 0 Oct 21 15:50 statm
-r--r--r--. 1 xxx xxx 0 Oct 21 15:50 status
-r--------. 1 xxx xxx 0 Oct 21 15:50 syscall
dr-xr-xr-x. 3 xxx xxx 0 Oct 21 15:50 task
-r--r--r--. 1 xxx xxx 0 Oct 21 15:50 timers
-rw-rw-rw-. 1 xxx xxx 0 Oct 21 15:50 timerslack_ns
-rw-r--r--. 1 xxx xxx 0 Oct 21 15:50 uid_map
-r--r--r--. 1 xxx xxx 0 Oct 21 15:50 wchan
CMD: ls -l /proc/94913/fd
total 0
lrwx------. 1 xxx xxx 64 Oct 21 15:50 0 -> /dev/pts/0
l-wx------. 1 xxx xxx 64 Oct 21 15:50 1 -> /tmp/out2
l-wx------. 1 xxx xxx 64 Oct 21 15:50 2 -> /tmp/out2
lr-x------. 1 xxx xxx 64 Oct 21 15:50 3 -> /dev/null
CMD: cat /proc/94913/status
Name:   pgm2
Umask:  0022
State:  S (sleeping)
Tgid:   94913
Ngid:   0
Pid:    94913
PPid:   94912
TracerPid:  0
Uid:    500 500 500 500
Gid:    500 500 500 500
FDSize: 64
Groups: 500
NStgid: 94913
NSpid:  94913
NSpgid: 94912
NSsid:  3771
VmPeak:     4136 kB
VmSize:     4136 kB
VmLck:         0 kB
VmPin:         0 kB
VmHWM:        80 kB
VmRSS:        80 kB
RssAnon:          80 kB
RssFile:           0 kB
RssShmem:          0 kB
VmData:       44 kB
VmStk:       132 kB
VmExe:         8 kB
VmLib:      1872 kB
VmPTE:        52 kB
VmSwap:        0 kB
HugetlbPages:          0 kB
CoreDumping:    0
Threads:    1
SigQ:   0/47895
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: 0000000000000000
SigIgn: 0000000000000000
SigCgt: 0000000000000000
CapInh: 0000000000000000
CapPrm: 0000000000000000
CapEff: 0000000000000000
CapBnd: 0000003fffffffff
CapAmb: 0000000000000000
NoNewPrivs: 0
Seccomp:    0
Speculation_Store_Bypass:   thread vulnerable
Cpus_allowed:   ff
Cpus_allowed_list:  0-7
Mems_allowed:   00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000001
Mems_allowed_list:  0
voluntary_ctxt_switches:    1
nonvoluntary_ctxt_switches: 0
fgets
Name:   pgm2
Umask:  0022
State:  S (sleeping)
Tgid:   94913
Ngid:   0
Pid:    94913
PPid:   94912
TracerPid:  0
Uid:    500 500 500 500
Gid:    500 500 500 500
FDSize: 64
Groups: 500
NStgid: 94913
NSpid:  94913
NSpgid: 94912
NSsid:  3771
VmPeak:     4136 kB
VmSize:     4136 kB
VmLck:         0 kB
VmPin:         0 kB
VmHWM:        80 kB
VmRSS:        80 kB
RssAnon:          80 kB
RssFile:           0 kB
RssShmem:          0 kB
VmData:       44 kB
VmStk:       132 kB
VmExe:         8 kB
VmLib:      1872 kB
VmPTE:        52 kB
VmSwap:        0 kB
HugetlbPages:          0 kB
CoreDumping:    0
Threads:    1
SigQ:   0/47895
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: 0000000000000000
SigIgn: 0000000000000000
SigCgt: 0000000000000000
CapInh: 0000000000000000
CapPrm: 0000000000000000
CapEff: 0000000000000000
CapBnd: 0000003fffffffff
CapAmb: 0000000000000000
NoNewPrivs: 0
Seccomp:    0
Speculation_Store_Bypass:   thread vulnerable
Cpus_allowed:   ff
Cpus_allowed_list:  0-7
Mems_allowed:   00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000001
Mems_allowed_list:  0
voluntary_ctxt_switches:    1
nonvoluntary_ctxt_switches: 0

postloop
elap=4 errkill=0 errst=0
CMD: ls -l /proc/94913
ls: cannot read symbolic link '/proc/94913/cwd': No such file or directory
ls: cannot read symbolic link '/proc/94913/root': No such file or directory
ls: cannot read symbolic link '/proc/94913/exe': No such file or directory
total 0
dr-xr-xr-x. 2 xxx  xxx  0 Oct 21 15:50 attr
-rw-r--r--. 1 root root 0 Oct 21 15:50 autogroup
-r--------. 1 root root 0 Oct 21 15:50 auxv
-r--r--r--. 1 root root 0 Oct 21 15:50 cgroup
--w-------. 1 root root 0 Oct 21 15:50 clear_refs
-r--r--r--. 1 root root 0 Oct 21 15:50 cmdline
-rw-r--r--. 1 root root 0 Oct 21 15:50 comm
-rw-r--r--. 1 root root 0 Oct 21 15:50 coredump_filter
-r--r--r--. 1 root root 0 Oct 21 15:50 cpuset
lrwxrwxrwx. 1 root root 0 Oct 21 15:50 cwd
-r--------. 1 root root 0 Oct 21 15:50 environ
lrwxrwxrwx. 1 root root 0 Oct 21 15:50 exe
dr-x------. 2 root root 0 Oct 21 15:50 fd
dr-x------. 2 root root 0 Oct 21 15:50 fdinfo
-rw-r--r--. 1 root root 0 Oct 21 15:50 gid_map
-r--------. 1 root root 0 Oct 21 15:50 io
-r--r--r--. 1 root root 0 Oct 21 15:50 latency
-r--r--r--. 1 root root 0 Oct 21 15:50 limits
-rw-r--r--. 1 root root 0 Oct 21 15:50 loginuid
dr-x------. 2 root root 0 Oct 21 15:50 map_files
-r--r--r--. 1 root root 0 Oct 21 15:50 maps
-rw-------. 1 root root 0 Oct 21 15:50 mem
-r--r--r--. 1 root root 0 Oct 21 15:50 mountinfo
-r--r--r--. 1 root root 0 Oct 21 15:50 mounts
-r--------. 1 root root 0 Oct 21 15:50 mountstats
dr-xr-xr-x. 2 xxx  xxx  0 Oct 21 15:50 net
dr-x--x--x. 2 root root 0 Oct 21 15:50 ns
-r--r--r--. 1 root root 0 Oct 21 15:50 numa_maps
-rw-r--r--. 1 root root 0 Oct 21 15:50 oom_adj
-r--r--r--. 1 root root 0 Oct 21 15:50 oom_score
-rw-r--r--. 1 root root 0 Oct 21 15:50 oom_score_adj
-r--------. 1 root root 0 Oct 21 15:50 pagemap
-r--------. 1 root root 0 Oct 21 15:50 personality
-rw-r--r--. 1 root root 0 Oct 21 15:50 projid_map
lrwxrwxrwx. 1 root root 0 Oct 21 15:50 root
-rw-r--r--. 1 root root 0 Oct 21 15:50 sched
-r--r--r--. 1 root root 0 Oct 21 15:50 schedstat
-r--r--r--. 1 root root 0 Oct 21 15:50 sessionid
-rw-r--r--. 1 root root 0 Oct 21 15:50 setgroups
-r--r--r--. 1 root root 0 Oct 21 15:50 smaps
-r--r--r--. 1 root root 0 Oct 21 15:50 smaps_rollup
-r--------. 1 root root 0 Oct 21 15:50 stack
-r--r--r--. 1 root root 0 Oct 21 15:50 stat
-r--r--r--. 1 root root 0 Oct 21 15:50 statm
-r--r--r--. 1 root root 0 Oct 21 15:50 status
-r--------. 1 root root 0 Oct 21 15:50 syscall
dr-xr-xr-x. 3 xxx  xxx  0 Oct 21 15:50 task
-r--r--r--. 1 root root 0 Oct 21 15:50 timers
-rw-rw-rw-. 1 root root 0 Oct 21 15:50 timerslack_ns
-rw-r--r--. 1 root root 0 Oct 21 15:50 uid_map
-r--r--r--. 1 root root 0 Oct 21 15:50 wchan
CMD: ls -l /proc/94913/fd
ls: cannot open directory '/proc/94913/fd': Permission denied
CMD: cat /proc/94913/status
Name:   pgm2
State:  Z (zombie)
Tgid:   94913
Ngid:   0
Pid:    94913
PPid:   94912
TracerPid:  0
Uid:    500 500 500 500
Gid:    500 500 500 500
FDSize: 0
Groups: 500
NStgid: 94913
NSpid:  94913
NSpgid: 94912
NSsid:  3771
Threads:    1
SigQ:   0/47895
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: 0000000000000000
SigIgn: 0000000000000000
SigCgt: 0000000000000000
CapInh: 0000000000000000
CapPrm: 0000000000000000
CapEff: 0000000000000000
CapBnd: 0000003fffffffff
CapAmb: 0000000000000000
NoNewPrivs: 0
Seccomp:    0
Speculation_Store_Bypass:   thread vulnerable
Cpus_allowed:   ff
Cpus_allowed_list:  0-7
Mems_allowed:   00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000001
Mems_allowed_list:  0
voluntary_ctxt_switches:    2
nonvoluntary_ctxt_switches: 0
fgets
Name:   pgm2
State:  Z (zombie)
Tgid:   94913
Ngid:   0
Pid:    94913
PPid:   94912
TracerPid:  0
Uid:    500 500 500 500
Gid:    500 500 500 500
FDSize: 0
Groups: 500
NStgid: 94913
NSpid:  94913
NSpgid: 94912
NSsid:  3771
Threads:    1
SigQ:   0/47895
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: 0000000000000000
SigIgn: 0000000000000000
SigCgt: 0000000000000000
CapInh: 0000000000000000
CapPrm: 0000000000000000
CapEff: 0000000000000000
CapBnd: 0000003fffffffff
CapAmb: 0000000000000000
NoNewPrivs: 0
Seccomp:    0
Speculation_Store_Bypass:   thread vulnerable
Cpus_allowed:   ff
Cpus_allowed_list:  0-7
Mems_allowed:   00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000001
Mems_allowed_list:  0
voluntary_ctxt_switches:    2
nonvoluntary_ctxt_switches: 0

postwait
elap=4 errkill=-1 errst=-1
CMD: ls -l /proc/94913
ls: cannot access '/proc/94913': No such file or directory
CMD: ls -l /proc/94913/fd
ls: cannot access '/proc/94913/fd': No such file or directory
CMD: cat /proc/94913/status
cat: /proc/94913/status: No such file or directory
fgets

Thanks. I'm (mildly) curious about the timing issues. If the wait-family call releases the information in /proc for the PID, then how does the process that launched the PID get to read the status pseudo-file after it knows the child terminated.

如果不使用wait, parent 就无法明确/轻松/干净地知道,因为检查实时进程的替代方法(例如,kill(pid,0)) 仍然返回 0。这让我 [有点] 感到惊讶。

根据测试程序输出,可能的一种方法是在 /proc/pid/cwd 上执行 readlink 并检查对于错误(即错误意味着进程退出并处于僵尸状态)。

另一种方法是读取 /proc/pid/status 并查找:State: Z (zombie)

Does it need to open the status file before the wait, and then read it once the wait returns?

wait 完成后,即使 pre/proc/pid/status 上打开的流也会返回 EOF。所以,没有快乐。

Or is it less devious than that? There should be some documentation on the /proc file system — proc(5) at man7.org for example — which should cover these details.

手册页还有一些其他文件,这些文件会在进程变成僵尸时更改(例如 /proc/pid/cmdline)

关于c - 如何从 PROC 获取有关子进程的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52918189/

相关文章:

c - C 中的长精确数字?

c - 从 C 中的多个整数创建 String(char*)

linux - 无法在 SUSE 11 上安装任何包

c - 如何从 Byte [] 中生成一个单词?

java - Java 中的 Hello World 程序未运行

linux - 如何配置串口波特率(/dev/ttySx)

process - 具体来说,将进程分成页面是什么意思?

c - C中使用管道在子进程之间传递数据

c# - Process.HasExited 竞争条件

c - 请教推荐Lua与C/C++协同工作的方式?