13. February 2012 08:00
This is a short example to show you how to read and write a process id to a file in linux.
First the write.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
int main(int argc, char **argv) {
pid_t pid = getpid();
if (argc < 2) {
printf("Usage: %s <filename>\n", argv[0]);
exit(EXIT_FAILURE);
}
FILE *fp = fopen(argv[1], "w");
if (!fp) {
perror("fopen");
exit(EXIT_FAILURE);
}
fprintf(fp, "%d\n", pid);
fclose(fp);
return EXIT_SUCCESS;
}
Then the read
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
int main(int argc, char **argv) {
pid_t pid = 0;
if (argc < 2) {
printf("Usage: %s <filename>\n", argv[0]);
exit(EXIT_FAILURE);
}
FILE *fp = fopen(argv[1], "r");
if (!fp) {
perror("fopen");
exit(EXIT_FAILURE);
}
if (fscanf(fp, "%d\n", &pid) == 1) {
printf("PID: %d\n", pid);
} else {
printf("Failed to Read PID\n");
}
fclose(fp);
return EXIT_SUCCESS;
}
da95cc4e-aee4-4c30-b108-7584facd2f72|0|.0