用C语言调用adduser命令

最近项目中需要用C语言实现Linux用户和用户组的创建,需要在C语言中调用adduser等命令。因为adduser这类命令需要在命令行中进行输入交互,不能通过system函数来实现,所以想要用进程管道来进行进程间的输入交互。

下面是我用进程管道实现的具体代码,希望对有类似需求的同学有帮助。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int adduser(char *user, char *home, char *passwd)
{
  int status = 0;
 
  FILE * fd = NULL;
 
  char cmd[1024] = {0};
  char param[256] = {0};
 
  /* get adduser shell command */
  sprintf(cmd, "adduser --home %s %s >> /dev/null 2>&1", home, user);
 
  fd = popen(cmd, "w");
  if (!fd) {
    printf("create adduser pipe failed.\n");
    return -1;
  }
 
  /* get password */
  sprintf(param, "%s\n", passwd);
 
  /* Enter new UNIX password */
  status = fwrite(param, 1, strlen(param), fd);
  if (status < 0) {
    printf("write pipe failed.\n");
    goto error;
  }
 
  /* Retype new UNIX password */
  status = fwrite(param, 1, strlen(param), fd);
  if (status < 0) {
    printf("write pipe failed.\n");
    goto error;
  }
 
  /* get other param */
  memset(param, 0, sizeof(param));
  sprintf(param, "\n\n\n\n\n\n");
 
  /* pass other options */
  status = fwrite(param, 1, strlen(param), fd);
  if (status < 0) {
    printf("write pipe failed.\n");
    goto error;
  }
 
  pclose(fd);
 
  /* check new user */
 
  memset(cmd, 0, sizeof(cmd));
  sprintf(cmd, "cat /etc/group | grep %s", user);
 
  fd = popen(cmd, "r");
  if (!fd) {
    printf("create check user pipe failed.\n");
    return -1;
  }
 
  status = fread(param, 1, sizeof(param), fd);
  if (status <= 0) {
    printf("adduser failed.\n");
    goto error;
  }
 
  pclose(fd);
 
  return 0;
 
error:
  pclose(fd);
 
  return -1;
}

int main(void)
{
  int status = 0;
  
  status = adduser("mm", "/home/zzs/work/test", "123123");
  if (!status) {
    printf("adduser success!!!\n");
  }
  
  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值