def forktest(): printf(1, "fork test\n") for n in range(1000): pid = fork() if pid < 0: break if pid == 0: exit_() if n == 1000: printf(1, "fork claimed to work 1000 times!\n") exit_() while n > 0: if wait() < 0: printf(1, "wait stopped early\n") exit_(1) n -= 1 if wait() != -1: printf(1, "wait got too many\n") exit_(1) printf(1, "fork test OK\n")
def main(): if open_("console", O_RDWR) < 0: mknod("console", 1, 1) open_("console", O_RDWR) dup(0) # stdout dup(0) # stderr while True: printf(1, "init: starting sh\n") pid = fork() if pid < 0: printf(1, "init: fork failed\n") exit() if pid == 0: exec_("sh", argv) printf(1, "init: exec sh failed\n") exit() while True: wpid = wait() if wpid < 0 or wpid == pid: break print(1, "zombie!\n")
def runcmd(cmd): p = [0, 0] if cmd == 0: exit_() if cmd.type == EXEC: ecmd = cmd if ecmd.argv[0] == 0: exit_() exec_(ecmd.argv[0], ecmd.argv) printf(2, "exec %s failed\n", ecmd.argv[0]) elif cmd.type == REDIR: rcmd = cmd close(rcmd.fd) if open_(rcmd.file, rcmd.mode) < 0: printf(2, "open %s failed\n", rcmd.file) exit_() runcmd(rcmd.cmd) elif cmd.type == LIST: lcmd = cmd # if fork1() == 0: # runcmd(lcmd.left) # wait() # runcmd(lcmd.right) fork1(runcmd, lcmd.left) wait() runcmd(lcmd.right) elif cmd.type == PIPE: pcmd = cmd if pipe(p) < 0: panic("pipe") if fork1() == 0: close(1) dup(p[1]) close(p[0]) close(p[1]) runcmd(pcmd.left) if fork1() == 0: close(0) dup(p[0]) close(p[0]) close(p[1]) runcmd(pcmd.right) close(p[0]) close(p[1]) wait() wait() elif cmd.type == BACK: bcmd = cmd if fork1() == 0: runcmd(bcmd.cmd) else: panic("runcmd") exit_()