2

I am running a fortran code on a cluster equiped with linux system. When the code begin to run, I want it to output some basic information of the node where it is running, especially the node name. How to do it in fortran.

user15964
  • 2,507
  • 2
  • 31
  • 57

2 Answers2

4

If your code is parallelised with MPI - which is kind of common for a code running on a cluster - then just call MPI_Get_processor_name() that just does exactly this. If not, just use the iso_c_binding module to call the C function gethostname(), which again just does that.

EDIT: here is an example on how to call gethostname() with the iso_c_binding module. I'm definitely not an expert with that so it might not be the most effective one ever...

module unistd
  interface
    integer( kind = C_INT ) function gethostname( hname, len ) bind( C, name = 'gethostname' )
        use iso_c_binding
        implicit none
        character( kind = C_CHAR ) :: hname( * )
        integer( kind = C_INT ), VALUE :: len
    end function gethostname
  end interface
end module unistd

program hostname
    use iso_c_binding
    use unistd
    implicit none
    integer( kind = C_INT ), parameter :: sl = 100
    character( kind = C_CHAR ) :: hn( sl )
    character( len = sl ) :: fn
    character :: c
    integer :: res, i, j

    res = gethostname( hn, sl )
    if ( res == 0 ) then 
        do i = 1, sl
            c = hn( i )
            if ( c == char( 0 ) ) exit
            fn( i: i ) = c
        end do
        do j = i, sl
            fn( j: j ) = ' '
        end do
        print *, "->", trim( fn ), "<-"
    else
        print *, "call to gethostname() didn't work..."
    end if
end program hostname
Gilles
  • 9,269
  • 4
  • 34
  • 53
  • Hi, Gilles. Thank you for answer. I can confirm `MPI_Get_processor_name()` works. But I am unable to get `gethostname()` to work, could you please give a code example on this? – user15964 May 02 '16 at 06:20
  • Oh, my god. It is really out of my expectation. I thought it must be a few lines... Anyway, as I tested, this works! I think I'd stick with MPI approach, or RussF's method is also very good. – user15964 May 02 '16 at 08:18
4

If the information you want is contained in an environment variable the easy way is just to get its value from a call to get_environment_variable. For the hostname

program gethost
character*32 hostname
call get_environment_variable('HOST',hostname)
write(*,*) 'My gracious host is ',trim(hostname)
end program gethost
RussF
  • 711
  • 3
  • 4