63 lines · c
1#include <fcntl.h>2#include <libgen.h>3#include <stdbool.h>4#include <stdint.h>5#include <stdio.h>6#include <stdlib.h>7#include <string.h>8#include <sys/errno.h>9#include <sys/param.h>10#include <sys/stat.h>11#include <unistd.h>12 13int get_return_value();14int get_return_value2();15 16// Create \a file_name with the c-string of our17// pid in it. Initially open & write the contents18// to a temporary file, then move it to the actual19// filename once writing is completed.20bool writePid(const char *file_name, const pid_t pid) {21 char *tmp_file_name = (char *)malloc(strlen(file_name) + 16);22 strcpy(tmp_file_name, file_name);23 strcat(tmp_file_name, "_tmp");24 int fd = open(tmp_file_name, O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR);25 if (fd == -1) {26 fprintf(stderr, "open(%s) failed: %s\n", tmp_file_name, strerror(errno));27 free(tmp_file_name);28 return false;29 }30 char buffer[64];31 snprintf(buffer, sizeof(buffer), "%ld", (long)pid);32 bool res = true;33 if (write(fd, buffer, strlen(buffer)) == -1) {34 fprintf(stderr, "write(%s) failed: %s\n", buffer, strerror(errno));35 res = false;36 }37 close(fd);38 39 if (rename(tmp_file_name, file_name) == -1) {40 fprintf(stderr, "rename(%s, %s) failed: %s\n", tmp_file_name, file_name,41 strerror(errno));42 res = false;43 }44 free(tmp_file_name);45 46 return res;47}48 49int main(int argc, char **argv) {50 if (writePid(argv[1], getpid())) {51 // we've signaled lldb we are ready to be attached to,52 // this sleep() call will be interrupted when lldb53 // attaches.54 sleep(200);55 } else {56 printf("Error writing pid to '%s', exiting.\n", argv[1]);57 exit(3);58 }59 60 int retval = get_return_value();61 return retval + get_return_value2();62}63