1.孤儿进程:没有父进程的进程,父进程退出,子进程不退出。
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
int a=10;
pid_t cpid = fork();
if(cpid>0)
{
printf("cpid=%d a=%d %p\n",cpid,a,&a);
}
else if(0==cpid)
{
while(1)
{
sleep(1);
}
}
else
{
perror("fork");
return -1;
}
return 0;
}
2.僵尸进程:父进程不退出,子进程退出。
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
int a=10;
pid_t cpid = fork();
if(cpid>0)
{
while(1)
{
sleep(1);
}
}
else if(0==cpid)
{
printf("cpid=%d a=%d %p\n",cpid,a,&a);
}
else
{
perror("fork");
return -1;
}
return 0;
}
3.外部输入一个路径,要求显示该路径下,所有文件的详细信息,除了隐藏文件。
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#include <pwd.h>
#include <grp.h>
#include <fcntl.h>
#include <dirent.h>
void Get_Permission(mode_t mode)
{
char per[]="rwx";
for(int i=0;i<9;i++)
{
if((mode & (0400>>i))==0)
{
putchar('-');
continue;
}
putchar(per[i%3]);
}
}
int getFileType(mode_t m)
{
switch(m&S_IFMT)
{
case S_IFSOCK: putchar('s'); break;
case S_IFLNK: putchar('l'); break;
case S_IFREG: putchar('-'); break;
case S_IFDIR: putchar('d'); break;
case S_IFBLK: putchar('b'); break;
case S_IFCHR: putchar('c'); break;
case S_IFIFO: putchar('p'); break;
default: printf("类型提取失败\n");
}
return 0;
}
void getfileUserName(uid_t uid)
{
struct passwd *pwd=getpwuid(uid);
if(NULL==pwd)
{
perror("getpwuid");
return;
}
printf("%s ",pwd->pw_name);
return;
}
void getfileGroupName(gid_t gid)
{
struct group *grp=getgrgid(gid);
if(NULL==grp)
{
perror("getgrgid");
return;
}
printf("%s ",grp->gr_name);
return;
}
int main(int argc, const char *argv[])
{
if(argc<2)
{
fprintf(stderr,"请输入文件名\n");
return -1;
}
DIR* dp = opendir(argv[1]);
if(NULL == dp)
{
perror("opendir");
return -1;
}
struct dirent* rp = NULL;
while(1)
{
rp = readdir(dp);
if(NULL == rp)
{
perror("readdir");
break;
}
char filename[30]="";
strcat(filename,argv[1]);
strcat(filename,rp->d_name);
if(rp->d_name[0] != '.')
{
struct stat buf;
char copy[20]="";
strcpy(copy,argv[1]);
if(stat(strcat(copy,rp->d_name),&buf)<0)
{
perror("stat");
return -1;
}
getFileType(buf.st_mode);
printf(" ");
Get_Permission(buf.st_mode);
printf(" ");
printf("%lu ",buf.st_nlink);
getfileUserName(buf.st_uid);
getfileGroupName(buf.st_gid);
printf("%ld ",buf.st_size);
struct tm* info = localtime(&buf.st_ctime);
if(NULL==info)
{
return -1;
}
char *Month[12] = {"一月", "二月", "三月", "四月", "五月", "六月","七月", "八月", "九月", "十月", "十一月", "十二月"};
printf("%s %02d %02d:%02d",\
Month[info->tm_mon],info->tm_mday,\
info->tm_hour,info->tm_min);
printf(" %s\n",rp->d_name);
}
}
closedir(dp);
return 0;
}