2

From man 2 clone:

SYNOPSIS

   /* Prototype for the glibc wrapper function */

   #define _GNU_SOURCE
   #include <sched.h>


   int clone(int (*fn)(void *), void *child_stack,
             int flags, void *arg, ...
             /* pid_t *ptid, void *newtls, pid_t *ctid */ );

RETURN VALUE
On success, the thread ID of the child process is returned in the caller's thread of execution. On failure, -1 is returned in the caller's context, no child process will be created, and errno will be set appropriately.

Since using pid_t as the return type

  1. improve the readability
  2. improve the maintainability
  3. is also capable of returning -1 when an error occurs

Why clone does not return pid_t, instead returns int?

JiaHao Xu
  • 2,452
  • 16
  • 31
  • The `ptid` parameter which is of type `pid_t` already contains the ID of the child thread. – P.W Jan 16 '19 at 06:45
  • @P.W Yes, but since it also returns the thread ID of the child process, why shouldn't it be `pid_t` instead of `int`? – JiaHao Xu Jan 16 '19 at 06:52
  • 1
    The type of `pid_t` is implementation defined. It does not have to be signed. If it is unsigned it cannot return -1. – P.W Jan 16 '19 at 07:04
  • 1
    @P.W If `pid_t` is unsigned, `fork()` and `vfork()` will be broken because they both return `-1` on failure and use `pid_t` as return type. – JiaHao Xu Jan 16 '19 at 07:06
  • Does the return value of clone always match what is stored in ptid? – P.W Jan 16 '19 at 07:24
  • @P.W For that to work, `CLONE_PARENT_SETTID` must be or-ed into the `flag`. So no, it does not always match. – JiaHao Xu Jan 16 '19 at 07:34
  • 1
    @P.W Linux requires a signed `pid_t`; [ref](https://stackoverflow.com/a/1931823/2410359) – chux - Reinstate Monica Jan 16 '19 at 18:27
  • Hmmm given "*nix" requirement of "The implementation shall support one or more programming environments in which the widths of blksize_t, pid_t, size_t, ssize_t, suseconds_t, and useconds_t are no greater than the width of type long.", I'd expect `clone()` to return `pid_t` or `long`. "Why clone does not return pid_t, instead returns int?" --> appears to be a not completely thought out design. I do not see an `int` advantage/rational. – chux - Reinstate Monica Jan 16 '19 at 18:31
  • @chux I agree with you on that. On the `Note` of the manpage of `clone`, it is shown that the underlying syscall `clone` returns `long`. – JiaHao Xu Jan 18 '19 at 03:10
  • @JiaHaoXu Perhaps it is worth submitting to GNU/Linux a request for change? – chux - Reinstate Monica Jan 18 '19 at 03:12
  • @chux It is. But how to? I haven't done anything like that before. – JiaHao Xu Jan 18 '19 at 03:33
  • @JiaHaoXu I do not know either. – chux - Reinstate Monica Jan 18 '19 at 04:03
  • @chux Maybe [FilingBug - glibc wiki](https://sourceware.org/glibc/wiki/FilingBugs) – JiaHao Xu Jan 18 '19 at 04:58

0 Answers0