應用說明:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <string.h> #include <time.h> struct INFO { char homeDir[128]; uid_t UID; gid_t GID; } currentInfo, targetInfo; int main(void) { char *fileName = "myFile.dat"; FILE *fp; time_t nowTime; time(&nowTime); memset(&targetInfo, 0, sizeof(struct INFO)); memset(¤tInfo, 0, sizeof(struct INFO)); targetInfo.UID = 501; targetInfo.GID = 101; strcpy(targetInfo.homeDir, "/home/dasusr1"); currentInfo.UID = getuid(); currentInfo.GID = getgid(); getcwd(currentInfo.homeDir, sizeof(currentInfo.homeDir)); if (setgid(targetInfo.GID) != -1) { if (setuid(targetInfo.UID) != -1) { chdir(targetInfo.homeDir); fp = fopen(fileName, "w"); if (fp != NULL) { fprintf(fp, "NOW:%s\n", ctime(&nowTime)); fclose(fp); } else { perror(fileName); } } else { perror(fileName); } setgid(currentInfo.GID); setuid(currentInfo.UID); chdir(currentInfo.homeDir); } return EXIT_SUCCESS; }