• Linux 进程基础


    传统的Linux模型里有三种创建或者修改进程的操作
    --system用于调用shell,执行一个指定的命令;
    --fork用于创建一个新的进程,该进程几乎是当前进程的一个完全拷贝;
    --exec可以在进程中用另外的程序来替换当前运行的进程。
    进程
    进程是一个正在执行的程序实例,他也是Linux基本的调度单位,一个进程由如下元素组成
    --进程的当前上下文(context),他是进程当前执行状态;
    --进程的当前执行目录;
    --进程访问的文件和目录;
    --程序的访问权限;
    --内存和其他分配给进程的系统资源;
    进程标识号
    --进程最知名的属性就是进程号(processID,PID)和它父进程号(parent processID,PPID).
    --PID和PPID都是非零的整数
    --一个PID唯一标识一个进程。
    --一个进程创建的另一个新进程称为子进程。相反的,创建子进程的进程称为父进程。
    --所有进程追溯其祖先最终都会落到进程号为1的进程身上,这个进程叫init进程
      -init进程是linux内核启动后第一个执行的程序。
      -init引导系统,启动守护进程并且运行必要的程序。
    获取PID和PPID
    pid_t getpid(void);
    pid_t getppid(void);
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <errno.h>
    #include <unistd.h>
    #include <sys/types.h>
    
    int main(int arg, char * args[])
    {
        printf("pid=%d
    ",getpid());
        printf("ppid=%d
    ",getppid());
        return 0;
    }
    getlogin函数返回执行程序的用户登录名。
    可以把登录名作为参数传递给getpwnam函数,这个函数能返回/etc/passwd文件中与该登录名相应的一行完成信息。
    struct passwd *getpwnam(const char *name);
    name必须是一个指向包含用户名的字符串指针。
    getpwnam返回一个指向passwd结构体的指针。
    struct passwd {
                   char   *pw_name;       /* username */
                   char   *pw_passwd;     /* user password */
                   uid_t   pw_uid;        /* user ID */
                   gid_t   pw_gid;        /* group ID */
                   char   *pw_gecos;      /* real name */
                   char   *pw_dir;        /* home directory */
                   char   *pw_shell;      /* shell program */
               };
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <errno.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <pwd.h>
    
    int main(int arg, char * args[])
    {
        //返回当前登录用户的属主名
        char * login=getlogin();
        printf("%s
    ",login);
        struct passwd * ps=getpwnam(login);
        printf("user name:%s
    ",ps->pw_name);
        //无法返回正确的用户密码
        printf("user password:%s
    ",ps->pw_passwd);
        printf("user ID:%d
    ",ps->pw_uid);
        //返回属主目录
        printf("home directory:%s
    ",ps->pw_dir);
    
        return 0;
    }
  • 相关阅读:
    3.24 每日一题题解
    3.23 每日一题题解
    3.22 每日一题题解
    【POJ1222】EXTENDED LIGHTS OUT
    【BZOJ1013】球形空间产生器sphere
    【hdu4135】【hdu2841】【hdu1695】一类通过容斥定理求区间互质的方法
    【HDU5862】Counting Intersections
    【HDU1542】Atlantis
    【自定义】抢妹子大作战
    【HDU5361】In Touch
  • 原文地址:https://www.cnblogs.com/zhanggaofeng/p/5808443.html
Copyright © 2020-2023  润新知