File: fork2.awk

package info (click to toggle)
gawk 1%3A4.2.1%2Bdfsg-1
  • links: PTS
  • area: main
  • in suites: buster
  • size: 20,880 kB
  • sloc: ansic: 50,919; awk: 12,043; yacc: 6,393; sh: 5,675; makefile: 2,856; sed: 128; csh: 6
file content (36 lines) | stat: -rw-r--r-- 1,032 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
@load "fork"

BEGIN {
   # avoid instantiating PROCINFO prior to the fork
   switch (pid = fork()) {
   case -1:
      printf "Error: fork failed with ERRNO %s\n", ERRNO
      exit 1
   case 0:
      # child
      fn = ("fork.tmp." PROCINFO["pid"])
      printf "pid %s ppid %s\n", PROCINFO["pid"], PROCINFO["ppid"] > fn
      exit 0
   default:
      # parent
      erc = 1
      fn = ("fork.tmp." pid)
      if ((rc = wait()) < 0)
	 printf "Error: wait failed with ERRNO %s\n", ERRNO
      else if (rc != pid)
	 printf "Error: wait returned %s instead of child pid %s\n", rc, pid
      else if ((getline x < fn) != 1)
	 printf "Error: getline failed on temp file %s\n", fn
      else {
	 close(fn)	# needed on non-POSIX systems
	 expected = ("pid " pid " ppid " PROCINFO["pid"])
	 if (x != expected)
	    printf "Error: child data (%s) != expected (%s)\n", x, expected
	 else if ((rc = system("rm  " fn)) != 0)
	    printf "Error removing temp file %s with ERRNO %s\n", fn, ERRNO
	 else
	    erc = 0
      }
      exit erc
   }
}