Hello. Interested in the next question. How to correctly get 4 fields in the / proc / self / stat file (4 fields is the pid of the process parent). in man proc it is written that the first three parameters are% d% s% c (if you use the scanf function). Our fourth is% d. But if you use spaces, brackets, other valid characters in the file name, in the simplest case, .out scanf (% * d% * s% * c% d)

cat / proc / 31707 / stat has the following output

31707 (kworker / u64: 1) S 2 0 0 0 -1 69247072 0 0 0 0 80 0 0 20 0 1 0 128062368 0 0 4294967295 0 0 0 0 0 0 0 2147483647 0 0 0 0 17 0 0 0 324 0 0 0 0 0 0 0 0 0

Therefore, the question arises how to correctly read the pid of the parent of a given process (not ours). As far as I know api there are none.

  • Read the status, there is a separate line and it is written what it is. But the question is really interesting, because there is really no other API and the standard ps uses the same proc files. The sources really have a big break in his search for how he does it - Mike
  • Yes, int ppid, n = fscanf(in, "%*d %*s %*s %d", &ppid); quite suitable (actually, you wrote it). And what is the question then? - avp
  • @avp And what will this scanf do when there is a space in the program name? I checked that the stat space is also not screened in any way and the round brackets in the file name are also quietly written in the file ... And by the way, the program should be called program) S 45 no one interferes - Mike
  • @Mike, well, I understood the problem (here you are, foolishness with spaces in the names, what freak it occurred to do that? (And the others picked up ...)). It is solved, obviously, by character reading with counting of parentheses before reading the closing and equality of the counter of their balance to zero. Then fscanf() - avp
  • @avp love files like that a. out))))) haha - rubeno4ka

1 answer 1

 ps -el | awk '{print $5}' 

If you need the PPID of a specific process - insert the appropriate grep between ps and awk

  • one
    and if in the name of the spaces it will also work? What actually all the discussion in the comments in question. - pavel
  • Actually, the question is about C, but if it is on the shell, then it is: sed 's/^.*)//' /proc/$PID/stat | awk '{ print $2 }' sed 's/^.*)//' /proc/$PID/stat | awk '{ print $2 }' - avp
  • getppid () - Sergey
  • Actually, when speaking about C - see the previous remark - just unsuccessfully pressed "Enter". I decided that the author needed a script, because he reads a FILE in the proc directory. If we are talking about the ppid of the current process, the simplest solution is getppid (). - Sergey
  • If we are talking about ppid of a certain "other" process, then looking for it by the name of the executable file is quite risky: - There may be several such processes - This may be a zombie So the problem with a space in the file name is not the biggest, in my opinion. - Sergey