=Start=
缘由:
整理学习在进行Linux下C编程中碰到的一些知识点,方便以后进行参考。
正文:
参考解答:
#include <stdio.h>#include <stdlib.h>#include <string.h>int main(int argc, char *argv[]){ FILE *stream; char *line = NULL; size_t len = 0; ssize_t nread; if (argc != 2) { fprintf(stderr, "Usage: %s <file>\n", argv[1]); exit(EXIT_FAILURE); } stream = fopen(argv[1], "r"); if (stream == NULL) { perror("fopen"); exit(EXIT_FAILURE); } while ((nread = getline(&line, &len, stream)) != -1) { printf("Retrieved line of length %zu:\n", nread); // fwrite(line, nread, 1, stdout); printf("strlen(line) = %d\n", strlen(line)); printf("sizeof(line) = %d\n", sizeof(line)); printf("%s\n", line); } printf("strlen(line) = %d\n", strlen(line)); printf("sizeof(line) = %d\n", sizeof(line)); printf("%s\n", line); free(line); fclose(stream); exit(EXIT_SUCCESS);} |
&
#include <stdio.h>#include <stdlib.h>int main(int argc, char **argv){ FILE *cmdline = fopen("/proc/self/cmdline", "rb"); char *arg = 0; size_t size = 0; while(getdelim(&arg, &size, 0, cmdline) != -1) { puts(arg); } free(arg); fclose(cmdline); return 0;} |
&
void read_proc(int process_pid) { char cmdline[1024], fname1[1024], ids[1024], fname2[1024], buf[1024]; int r = 0, fd, i; FILE *f = NULL; snprintf(fname1, sizeof(fname1), "/proc/%d/status", process_pid); f = fopen(fname1, "r"); memset(&ids, 0, sizeof(ids)); while (f && fgets(buf, sizeof(buf), f) != NULL) { if (strstr(buf, "Uid")) { strtok(buf, "\n"); snprintf(ids, sizeof(ids), "%s", buf); } } if (f) fclose(f); snprintf(fname2, sizeof(fname2), "/proc/%d/cmdline", process_pid); fd = open(fname2, O_RDONLY); memset(&cmdline, 0, sizeof(cmdline)); if (fd > 0) { r = read(fd, cmdline, sizeof(cmdline)); close(fd); for (i = 0; r > 0 && i < r-1; ++i) { if (cmdline[i] == 0) cmdline[i] = ' '; } } printf("EXEC:pid=%d\t[%s]\t[%s]\n", process_pid, ids, cmdline);} |
参考链接:
- http://man7.org/linux/man-pages/man3/getline.3.html
- http://man7.org/linux/man-pages/man5/proc.5.html
- https://stackoverflow.com/questions/15545341/process-name-from-its-pid-in-linux/22214304#22214304
- http://users.suse.com/~krahmer/exec-notify.c
=END=