You have perhaps, by now, thought okay, but how exactly do I set these special permission bits?
This is simple: you use the chmod(1) command (or system call); this table shows how chmod can be used to set the setuid/setgid permission bits:
chmod via: | Notation for setuid | Notation for setgid |
symbolic notation | u+s | g+s |
octal notation | 4<octal #> (eg. 4755) | 2<octal #> (eg. 2755) |
As a trivial example, take a simple Hello, world C program and compile it:
gcc hello.c -o hello
Now we set the setuid bit, then remove it, and set the setgid bit instead (in one operation: via the u-s,g+s parameter to chmod), then remove the setgid bit, all the while long-listing the binary executable so that the permissions can be seen:
$ ls -l hello
-rwxrwxr-x 1 seawolf seawolf 8336 Feb 17 19:02 hello
$ chmod u+s hello ; ls -l hello
-rwsrwxr-x 1 seawolf seawolf 8336 Feb 17 19:02 hello
$ chmod u-s,g+s hello ; ls -l hello
-rwxrwsr-x 1 seawolf seawolf 8336 Feb 17 19:02 hello
$ chmod g-s hello ; ls -l hello
-rwxrwxr-x 1 seawolf seawolf 8336 Feb 17 19:02 hello
$
(As this Hello, world program just trivially prints to stdout and nothing more, the setuid/setgid bits have no perceived effect.)