On the railroads, a flagman is an employee of the railroad who is assigned to protect contractors or anyone performing work on a railroad right of way. A flagman is also assigned to protect a train that has stopped on a section of track. When a train approaches a location a flagman is posted, the train crew will have to get permission from the flagman to pass the area.
Before the advent of automated level crossing gates, and still where automatic gates are not installed, flagmen were also assigned to protect the crossings. The flagman would stop road traffic from crossing the tracks as trains used the crossing.
Rules pertaining to a flagman may vary depending on different railroad's operating rules. For instance on CSX Transportation a train approaching the work area is to call the flagman for permission through the work area. If workers are in the clear the flagman will advise crew to proceed and advise the crew that workers are not fouling the track. If a flagman fails to answer, the train crew is required by rule to stop short of milepost location and proceed at restricted speed. However on Norfolk Southern there are no flagmen. Rather NS has a track supervisor obtain track authority from the train dispatcher to take the track out of service until it is certain that workers are in the clear and trains may safely pass the area.
...every company... operating a railroad within this state, shall construct and maintain a gate or gates, or bridge, or maintain a flagman to signal trains at every highway or street crossing...