1 /*
2 * This file is part of attach-p-cmd strace test.
3 *
4 * Copyright (c) 2016-2021 Dmitry V. Levin <ldv@strace.io>
5 * All rights reserved.
6 *
7 * SPDX-License-Identifier: GPL-2.0-or-later
8 */
9
10 #include "tests.h"
11 #include <errno.h>
12 #include <signal.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <sys/stat.h>
16 #include <time.h>
17 #include <unistd.h>
18 #include "attach-p-cmd.h"
19
20 static void
21 wait_for_peer_invocation(void)
22 {
23 /* create the lock directory */
24 if (mkdir(lockdir, 0700))
25 perror_msg_and_fail("mkdir: %s", lockdir);
26
27 /* wait for the lock directory to be removed by peer */
28 while (mkdir(lockdir, 0700)) {
29 if (EEXIST != errno)
30 perror_msg_and_fail("mkdir: %s", lockdir);
31 }
32
33 /* cleanup the lock directory */
34 if (rmdir(lockdir))
35 perror_msg_and_fail("rmdir: %s", lockdir);
36 }
37
38 static void
39 wait_for_peer_termination(void)
40 {
41 FILE *fp = fopen(pidfile, "r");
42 if (!fp)
43 perror_msg_and_fail("fopen: %s", pidfile);
44
45 pid_t pid;
46 if (fscanf(fp, "%d", &pid) < 0)
47 perror_msg_and_fail("fscanf: %s", pidfile);
48 if (pid < 0)
49 error_msg_and_fail("pid = %d", pid);
50
51 if (fclose(fp))
52 perror_msg_and_fail("fclose: %s", pidfile);
53
54 if (unlink(pidfile))
55 perror_msg_and_fail("unlink: %s", pidfile);
56
57 while (kill(pid, 0) == 0)
58 ;
59 }
60
61 int
62 main(void)
63 {
64 wait_for_peer_invocation();
65 wait_for_peer_termination();
66
67 static const struct timespec ts = { .tv_nsec = 123456789 };
68 if (nanosleep(&ts, NULL))
69 perror_msg_and_fail("nanosleep");
70
71 static const char dir[] = "attach-p-cmd.test -p";
72 pid_t pid = getpid();
73 int rc = chdir(dir);
74
75 printf("%-5d chdir(\"%s\") = %s\n"
76 "%-5d +++ exited with 0 +++\n",
77 pid, dir, sprintrc(rc), pid);
78
79 return 0;
80 }