sticky bit

本日はAPUE Chapter5のsection4.10 Sticky Bitを読んでおります。

On contemporary systems, the use of the sticky bit has been extended. The Single UNIX Specification allows the sticky bit to be set for a directory. If the bit is set for a directory, a file in the directory can be removed or renamed only if the user has write permission for the directory and one of the following:
- Owns the file
- Owns the directory
- Is the superuser

The directories /tmp and /var/spool/uucppublic are typical candidate for the sticky bit.

要約すると、Sticky Bitが立っているディレクトリ内ファイルは write権限あり && (ファイル所有者 || ディレクトリ所有者 || スーパーユーザ)じゃないと削除できないよ、ということですね。


例えば/tmpは以下のように777パーミッション+Stick Bit("t")という権限になってます。

drwxrwxrwt   62 root root 20480 Mar 24 13:30 tmp/


Cでやるならこんな風かな。

#include <stdio.h>
#include <sys/stat.h>

int main(int argc, char* argv[])
{
  struct stat buf;
  stat("/tmp", &buf);
  
  if ( buf.st_mode & S_ISVTX ) {                                                                                                                                    
      printf("Sticky Bit: ON\n");                                                                                                                                   
  } 
}

まとめ

Stick Bitのことがちょっとだけわかるようになりました。