child from user, how?

hello everybody,
I've a test programm which create child with new pid, but how ran new child from user if parent runing from root?
For instanse, I need bind low tcp port(which > 1024) with root privileges and then send\recv data with user privilages.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int     glob = 6;
char    buf[] = "a write to stdout\n";
int
main(void)
{
    int       var;      /* automatic variable on the stack */
    pid_t     pid;
    var = 88;
    if (write(STDOUT_FILENO, buf, sizeof(buf)-1) != sizeof(buf)-1)
        printf("write error\n");
    printf("before fork\n");    /* we don't flush stdout */
    if ((pid = fork()) < 0) {
        printf("fork error\n");
    } else if (pid == 0) {      /* child */
        glob++;                 /* modify variables */
        var++;
    } else {
        sleep(20);               /* parent */
    }
    printf("pid = %d, glob = %d, var = %d\n", getpid(), glob, var);
    exit(0);
}

man setuid and seteuid

EDIT: also getpwnam, you'll need it to convert user name to ID to pass to one of the above two functions.
Last edited on
ok, I wrote this function which's returning uid, but how I can use it with fork so as to start new child from my user?
1
2
3
4
5
6
int getusr(){
     struct passwd    *ptr;
     if ((ptr = getpwnam("quant")) == NULL)
         printf("getpwnam error\n");
     return(ptr->pw_uid);
}

please, give me sample how I can use this with fork.
After you fork(), in the child process call setuid() or seteuid() (as appropriate) giving it the uid you just looked up, and now the child process will be executing as that user id instead of root.
Topic archived. No new replies allowed.