Search code examples
cunixterminaltty

Process that toggles other's permission to write to your terminal [Unix] [C]


I'm working on a process that lets a user allow or disallow others from writing to their terminal. Below is what I have but it does not appear to be working, I'm not sure why. If anybody could point me in the right direction I would appreciate it.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>

main( int ac, char *av[] ){
  struct stat settings;
  int perms;

  if ( fstat(0, &settings) == -1 ){
    perror("Cannot stat stdin");
    exit(0);
  }

  perms = (settings.st_mode & 07777);

  if ( ac == 1 ){
    printf("Other's write is %s\n", (perms & S_IWOTH)?"On":"Off");
    exit(0);
  }

  if ( ac == 2 && av[1][0] == 'n' )
    perms &= ~S_IWOTH;
  else
    perms &= S_IWOTH;
  fchmod(0, perms);
  return 0;
}

Solution

  • You probably meant to do

    perms |= S_IWOTH;
    

    rather than

    perms &= S_IWOTH;
    

    &'ing with S_IWOTH will clear all bits that aren't S_IWOTH, and will leave that bit as zero too if it wasn't already set.

    You can run tty(1) to get the filename of your terminal and run ls -l on it to see the permissions by the way, in case you didn't already know that. Don't forget that the group permissions might be important too.

    It would be a good idea to check the return value of fchmod(2) too.